package p.studio.workspaces.assets.tiled;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.*;

final class TiledXmlCodecTest {
    private final TiledXmlCodec codec = new TiledXmlCodec();

    @TempDir
    Path tempDir;

    @Test
    void readsFixtureTmxAndPreservesWaveOneSurfaces() throws Exception {
        final TiledMapDocument map = codec.readMap(Path.of("..", "test-projects", "main", "assets", "scenes", "primeiro mapa.tmx").toAbsolutePath().normalize());

        assertEquals(25, map.width());
        assertEquals(25, map.height());
        assertEquals(1, map.tilesets().size());
        assertEquals("../Zelda3/primeiro tileset.tsx", map.tilesets().getFirst().source());
        assertEquals(1, map.tileLayers().size());
        assertEquals(625, map.tileLayers().getFirst().gids().size());
        assertEquals(1, map.objectLayers().size());
        assertEquals(9, map.objectLayers().getFirst().objects().size());
    }

    @Test
    void readsFixtureTsxWithPropertiesAndCollisionObjects() throws Exception {
        final TiledTilesetDocument tileset = codec.readTileset(Path.of("..", "test-projects", "main", "assets", "Zelda3", "primeiro tileset.tsx").toAbsolutePath().normalize());

        assertEquals(32, tileset.tileWidth());
        assertEquals(32, tileset.tileHeight());
        assertEquals(13, tileset.tileCount());
        assertEquals(13, tileset.tiles().size());
        assertEquals("glyph_id", tileset.tiles().getFirst().properties().getFirst().name());
        assertNotNull(tileset.tiles().getFirst().collisionLayer());
        assertEquals(2, tileset.tiles().getFirst().collisionLayer().objects().size());
    }

    @Test
    void rejectsUnsupportedInfiniteMaps() throws Exception {
        final Path path = tempDir.resolve("infinite.tmx");
        Files.writeString(path, """
                <?xml version="1.0" encoding="UTF-8"?>
                <map version="1.10" tiledversion="1.12.1" orientation="orthogonal" renderorder="right-down"
                     width="10" height="10" tilewidth="16" tileheight="16" infinite="1"/>
                """);

        assertThrows(TiledUnsupportedFeatureException.class, () -> codec.readMap(path));
    }
}
