package space.animefu.starfallhaven;

import android.content.Context;
import java.io.*;

/** Atomic app-private persistence. A failed write never replaces the last good colony. */
public final class GameSaveStore {
    private static final String SAVE="colony-v1.bin", TEMP="colony-v1.tmp";
    private final File directory;
    public GameSaveStore(Context context){directory=context.getFilesDir();}
    public synchronized boolean hasSave(){return new File(directory,SAVE).isFile();}
    public synchronized GameWorld load() throws IOException,GameWorldSave.SaveException {
        File f=new File(directory,SAVE);if(!f.isFile())return null;
        try(FileInputStream in=new FileInputStream(f);ByteArrayOutputStream out=new ByteArrayOutputStream()){
            byte[] buffer=new byte[8192];int n;while((n=in.read(buffer))!=-1){out.write(buffer,0,n);if(out.size()>2_000_000)throw new IOException("Save is too large");}
            return GameWorldSave.decode(out.toByteArray());
        }
    }
    public synchronized void save(GameWorld world) throws IOException,GameWorldSave.SaveException {
        byte[] data=GameWorldSave.encode(world);File temp=new File(directory,TEMP),target=new File(directory,SAVE);
        try(FileOutputStream out=new FileOutputStream(temp)){out.write(data);out.flush();out.getFD().sync();}
        if(!temp.renameTo(target)){try(FileOutputStream out=new FileOutputStream(target)){out.write(data);out.flush();out.getFD().sync();}if(!temp.delete())temp.deleteOnExit();}
    }
}
