package id.iptek.utms.agent.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author jakar
 */
public class FileReaderCacheObj implements Serializable {
    
    private File file;
    private BufferedReader reader;
    private final AtomicInteger currentReadRowNum = new AtomicInteger(0);

    public FileReaderCacheObj() {
    }

    /**
     * @return the file
     */
    public File getFile() {
        return file;
    }

    /**
     * @param file the file to set
     */
    public void setFile(File file) {
        this.file = file;
    }

    /**
     * @return the reader
     */
    public BufferedReader getReader() {
        return reader;
    }

    /**
     * @return the currentReadRowNum
     */
    public AtomicInteger getCurrentReadRowNum() {
        return currentReadRowNum;
    }
    
    public void pointToFile(File file) throws IOException {
        if(file == null) {
            throw new IllegalArgumentException("File cannot be null!");
        }
        if(!file.exists()) {
            throw new IOException("File not exists!");
        }
        if(!file.canRead()) {
            throw new IOException("File not readable!");
        }
        this.file = file;
        this.reader = new BufferedReader(new FileReader(this.file));
        this.currentReadRowNum.set(0);
    }
    
    public void closeReader() throws IOException {
        if(this.reader != null) {
            this.reader.close();
            this.file = null;
            this.currentReadRowNum.set(0);
        } else {
            // ignore null reader
        }
    }
}
