package com.jdblabs.timestamper.core;

import com.jdbernard.util.SmartConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 *
 * @author Jonathan Bernard ({@literal jdbernard@gmail.com})
 */
public class FileTimelineSource extends TimelineSource {

    private File file;

    public FileTimelineSource(URI uri, SmartConfig config) {
        super(uri);
        this.file = new File(uri);
    }

    /** * {@inheritDoc } */
    public Timeline read() throws IOException {
        FileInputStream fin = new FileInputStream(file);
        Timeline t = StreamBasedTimelineSource.readFromStream(fin);
        fin.close();
        return t;
    }

    public Timeline readWithComments(OutputStream commentStream)
    throws IOException {
        FileInputStream fin = new FileInputStream(file);
        Timeline t = StreamBasedTimelineSource.readFromStream(fin, commentStream);
        fin.close();
        return t;
    }

    /** * {@inheritDoc } */
    public void persist(Timeline t) throws IOException {
        FileOutputStream fout = new FileOutputStream(file);
        StreamBasedTimelineSource.writeToStream(fout, t);
        fout.close();
    }

    public boolean isAuthenticated() {
        File dir = file.getParentFile();
        return (dir.canRead() && dir.canWrite());
    }

    public void authenticate() throws AuthenticationException {
        File dir = file.getParentFile();
        if (!dir.canRead())
            throw new AuthenticationException("This FileTimelineSource does not"
                    + " have read access to the parent directory for the "
                    + "given file (" + file.getAbsolutePath() + ".");

        if (!dir.canWrite())
            throw new AuthenticationException("This FileTimelineSource does not"
                    + " have write access to the parent directory for the "
                    + "given file (" + file.getAbsolutePath() + ".");

    }
}
