// Carnegie Mellon University
//   Information Networking Institute and
//   School of Computer Science
//
// Master Thesis: A Monitoring Tool for Overlay Network
// By: TungFai Chan and Annie Cheng
//
// File: Disk.java
// Path: eventbase/virtualMemory
// Description: Simulate disk operation

package eventbase.virtualMemory;

import java.io.*;
import java.util.*;

public class Disk {

    final static String VIRTUAL_MEMORY_PATH = "./swap.file";

    RandomAccessFile randAccFile = null;

    public Disk() throws IOException {
        File file = new File(VIRTUAL_MEMORY_PATH);

        randAccFile = new RandomAccessFile(file, "rw");

        if (!file.exists())
            // TODO: Is this necessary? - tungfai
            createDisk();

    }

    public Page readPage(int id) throws IOException {
        int startPos = id * Page.NUM_RECORD_PER_PAGE * Record.MAX_LENGTH;
        Page rtnPage = null;

        randAccFile.seek(startPos);
        byte[] buffer = new byte[Page.NUM_RECORD_PER_PAGE * Record.MAX_LENGTH];
        randAccFile.readFully(buffer);
        rtnPage = new Page(id, buffer);

        return rtnPage;
    }

    public void writePage(Page page) throws IOException {
        if (!page.dirty)
            return;

        int startPos = page.getPageID() * Page.NUM_RECORD_PER_PAGE * Record.MAX_LENGTH;

        randAccFile.seek(startPos);
        randAccFile.write(page.getBytes());

        System.out.println("Write Page ID: " + page.getPageID());

    }

    public void close() throws IOException {
        randAccFile.close();
    }

    private void createDisk() throws IOException {
        //Seek to the end
        randAccFile.seek(1000000);
        randAccFile.writeBytes("\0");
        randAccFile.seek(0);
    }

}