using Minint.Core.Models;

namespace Minint.Core.Services.Impl;

public sealed class ImageEffectsService : IImageEffectsService
{
    public void ApplyContrast(MinintDocument doc, double factor)
    {
        for (int i = 1; i < doc.Palette.Count; i++)
        {
            var c = doc.Palette[i];
            doc.Palette[i] = new RgbaColor(
                ContrastByte(c.R, factor),
                ContrastByte(c.G, factor),
                ContrastByte(c.B, factor),
                c.A);
        }
        doc.InvalidatePaletteCache();
    }

    public void ApplyGrayscale(MinintDocument doc)
    {
        for (int i = 1; i < doc.Palette.Count; i++)
        {
            var c = doc.Palette[i];
            byte gray = (byte)Math.Clamp((int)(0.299 * c.R + 0.587 * c.G + 0.114 * c.B + 0.5), 0, 255);
            doc.Palette[i] = new RgbaColor(gray, gray, gray, c.A);
        }
        doc.InvalidatePaletteCache();
    }

    private static byte ContrastByte(byte value, double factor)
    {
        double v = ((value / 255.0) - 0.5) * factor + 0.5;
        return (byte)Math.Clamp((int)(v * 255 + 0.5), 0, 255);
    }
}
