using Minint.Core.Models;
using Minint.Core.Services.Impl;

namespace Minint.Tests;

public class FragmentServiceTests
{
    private readonly FragmentService _fragment = new();

    [Fact]
    public void CopyFragment_SameDocument_CopiesPixels()
    {
        var doc = new MinintDocument("test");
        var red = new RgbaColor(255, 0, 0, 255);
        doc.EnsureColorCached(red);

        var src = new MinintLayer("src", 16);
        src.Pixels[0] = 1; // (0,0) = red
        src.Pixels[1] = 1; // (1,0) = red
        doc.Layers.Add(src);

        var dst = new MinintLayer("dst", 16);
        doc.Layers.Add(dst);

        _fragment.CopyFragment(doc, 0, 0, 0, 2, 1, doc, 1, 2, 2, 4, 4);

        Assert.Equal(1, dst.Pixels[2 * 4 + 2]); // (2,2)
        Assert.Equal(1, dst.Pixels[2 * 4 + 3]); // (3,2)
    }

    [Fact]
    public void CopyFragment_DifferentDocuments_MergesPalette()
    {
        var srcDoc = new MinintDocument("src");
        var blue = new RgbaColor(0, 0, 255, 255);
        int blueIdx = srcDoc.EnsureColorCached(blue);
        var srcLayer = new MinintLayer("L1", 4);
        srcLayer.Pixels[0] = blueIdx;
        srcDoc.Layers.Add(srcLayer);

        var dstDoc = new MinintDocument("dst");
        var dstLayer = new MinintLayer("L1", 4);
        dstDoc.Layers.Add(dstLayer);

        _fragment.CopyFragment(srcDoc, 0, 0, 0, 1, 1, dstDoc, 0, 0, 0, 2, 2);

        int dstBlueIdx = dstDoc.FindColorCached(blue);
        Assert.True(dstBlueIdx > 0);
        Assert.Equal(dstBlueIdx, dstLayer.Pixels[0]);
    }

    [Fact]
    public void CopyFragment_TransparentPixels_Skipped()
    {
        var doc = new MinintDocument("test");
        var src = new MinintLayer("src", 4); // all zeros (transparent)
        doc.Layers.Add(src);

        var dst = new MinintLayer("dst", 4);
        Array.Fill(dst.Pixels, 0);
        dst.Pixels[0] = 0; // explicitly 0
        doc.Layers.Add(dst);

        _fragment.CopyFragment(doc, 0, 0, 0, 2, 2, doc, 1, 0, 0, 2, 2);

        Assert.Equal(0, dst.Pixels[0]); // stays transparent
    }
}
