package space.animefu.starfallhaven;

import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import static org.junit.Assert.*;

public final class V3RegionalPersistenceTest {
    @Test public void regionalFactionAndLandingStateRoundTripExactly()throws Exception{
        GameWorld world=new GameWorld(551122);RegionalMap.Cell choice=world.regionalMap.validLandingSites().get(3);
        assertTrue(world.selectLandingSite(choice.x,choice.y));assertTrue(world.confirmLandingSite());
        world.factionSimulation.changeStanding("skyloom",-19);world.factionSimulation.advanceTurn();world.factionSimulation.advanceTurn();
        FactionSimulation.Settlement before=world.factionSimulation.settlements().get(0);
        byte[] encoded=GameWorldSave.encode(world);GameWorld restored=GameWorldSave.decode(encoded);
        assertEquals(4,GameWorldSave.VERSION);assertEquals(world.worldSeed,restored.worldSeed);assertEquals(choice.x,restored.selectedLandingX);assertEquals(choice.y,restored.selectedLandingY);assertTrue(restored.landingSiteConfirmed);
        assertEquals(world.regionalMap.cell(7,5).biome,restored.regionalMap.cell(7,5).biome);
        assertEquals(world.factionSimulation.strategicTurn,restored.factionSimulation.strategicTurn);
        assertEquals(world.factionSimulation.faction("skyloom").standing,restored.factionSimulation.faction("skyloom").standing);
        FactionSimulation.Settlement after=restored.factionSimulation.settlements().get(0);assertEquals(before.population,after.population);assertEquals(before.prosperity,after.prosperity);assertEquals(before.lastStrategy,after.lastStrategy);
        assertArrayEquals(encoded,GameWorldSave.encode(restored));
    }

    @Test public void frozenV2MigratesDeterministicallyWithoutChangingColonyState()throws Exception{
        byte[] fixture=resource("/saves/v2-qualified.bin");GameWorld first=GameWorldSave.decode(fixture),second=GameWorldSave.decode(fixture);
        assertEquals(81,first.wood);assertEquals(6,first.day);assertEquals(.42f,first.timeOfDay,0);assertTrue(first.landingSiteConfirmed);
        assertNotNull(first.regionalMap);assertNotNull(first.factionSimulation);assertEquals(first.day-1,first.factionSimulation.strategicTurn);
        assertEquals(first.selectedLandingX,second.selectedLandingX);assertEquals(first.selectedLandingY,second.selectedLandingY);
        assertArrayEquals(GameWorldSave.encode(first),GameWorldSave.encode(second));
    }
    private byte[] resource(String path)throws Exception{try(InputStream in=getClass().getResourceAsStream(path)){assertNotNull(in);ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] buffer=new byte[4096];int n;while((n=in.read(buffer))>=0)out.write(buffer,0,n);return out.toByteArray();}}
}
