package lc.mecha.io;

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

/**
 * Simple class for handling straightforward persistent cases. The central purpose of this class is to provide
 * interruption-proof "safe" mechanics, provided that the underlying filesystem is synchronized appropriately.
 *
 * @author Alex Leigh
 */
public class ObjectPersister {
    private final Path outputPath;

    public ObjectPersister(Path outputPath) {
        this.outputPath = outputPath;
        outputPath.toFile().mkdirs();
    }

    public void write(Serializable object) throws IOException {
        File tmpFile = File.createTempFile("persistent", "obj");
        try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)))) {
            oos.writeObject(object);
        }
        Files.move(tmpFile.toPath(), outputPath, StandardCopyOption.REPLACE_EXISTING);
    }

    public Path getOutputPath() {
        return outputPath;
    }

    public Object read() throws IOException, ClassNotFoundException {
        File dbf = outputPath.toFile();
        if (!dbf.isFile()) {
            return null;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dbf)))) {
            return ois.readObject();
        }
    }
}
