package lc.mecha.io;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class OutputFile {
    private final Path filename;
    private final Path tmpFile;
    private final OutputStream os;

    public OutputFile(Path filename, Path tmpFile) throws FileNotFoundException {
        this.filename = filename;
        this.tmpFile = tmpFile;
        os = new BufferedOutputStream(new FileOutputStream(tmpFile.toFile()));
    }

    public OutputStream getOutputStream() {
        return os;
    }

    public Path getFilename() {
        return filename;
    }

    public void commit() throws IOException {
        os.close();
        Files.move(tmpFile, filename, StandardCopyOption.REPLACE_EXISTING);
    }
}
