package p.packer.repositories;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.packer.models.PackerAssetCacheEntry;
import p.packer.models.PackerFileCacheEntry;
import p.packer.models.PackerTileIndexedV1;
import p.packer.models.PackerGlyphBankRequirements;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

final class PackerGlyphBankWalkerTest {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @TempDir
    Path tempDir;

    @Test
    void invalidatesCachedTileMetadataWhenPaletteIndicesAreMissing() throws Exception {
        final Path assetRoot = Files.createDirectories(tempDir.resolve("asset"));
        final Path filePath = assetRoot.resolve("tile.png");
        writeTile(filePath);

        final PackerGlyphBankWalker walker = new PackerGlyphBankWalker(MAPPER);
        final PackerAssetCacheEntry priorCache = new PackerAssetCacheEntry(
                1,
                "contract",
                List.of(new PackerFileCacheEntry(
                        "tile.png",
                        "image/png",
                        Files.size(filePath),
                        Files.getLastModifiedTime(filePath).toMillis(),
                        null,
                        Map.of(
                                "tile", Map.of("width", 16, "height", 16),
                                "palette", Map.of("originalArgb8888", List.of(0xFFFFFFFF))),
                        List.of())));

        final var result = walker.walk(assetRoot, new PackerGlyphBankRequirements(16), Optional.of(priorCache));

        final PackerTileIndexedV1 tile = (PackerTileIndexedV1) result.probeResults().getFirst().metadata().get("tile");
        assertNotNull(tile);
        assertTrue(tile.paletteIndices().length > 0);
    }

    private void writeTile(Path path) throws Exception {
        final BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
        for (int y = 0; y < 16; y++) {
            for (int x = 0; x < 16; x++) {
                image.setRGB(x, y, (x + y) % 2 == 0 ? 0xFFFF0000 : 0xFF00FF00);
            }
        }
        ImageIO.write(image, "png", path.toFile());
    }
}
