using Hawkeye.VisionBuilder.Workflow.Datatypes;
using Hawkeye.VisionBuilder.Workflow.Operations.Attributes;
using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.Operations.Filters;
[Category("Filters")]
public class LUTFilterOperation : BaseOperation
{



    public LutData LutData { get; set; } = new LutData();

    [NotForTool]
    public HawkeyeImage LastImage { get; set; } = null;

    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;

        LastImage = context.ActiveImage;
        var mat = context.ActiveImage.ImageData;
        if (mat.Channels() == 3)
        {
            Mat[] tmp = new Mat[3];
            Span<byte> span = new Span<byte>(LutData.LUT);
            for (int i = 0; i < 3; i++)
            {
                var channel = mat.ExtractChannel(i);

                tmp[i] = channel.LUT(span[(i * 256)..((i + 1) * 256)].ToArray());
            }

            mat = new Mat(mat.Size(), mat.Type());
            Cv2.Merge(tmp, mat);

        }

        if (mat.Channels() == 1)
        {
            Span<byte> span = new Span<byte>(LutData.LUT);
            mat = mat.LUT(span[0..256].ToArray());
        }
        context.ActiveImage = new HawkeyeImage() { ImageData = mat };
        Status = "";
        Result = true;
    }

    public override void Save(BinaryWriter bw)
    {
        base.Save(bw);
        LutData.Serialize(bw);
    }

    public override void Load(BinaryReader br)
    {
        base.Load(br);
        LutData.Deserialize(br);
    }

    public override void Save(Dictionary<string, object> dict)
    {
        base.Save(dict);
        // Save LutData as serialized representation
        using var ms = new MemoryStream();
        using var bw = new BinaryWriter(ms);
        LutData.Serialize(bw);
        dict[nameof(LutData)] = Convert.ToBase64String(ms.ToArray());
    }

    public override void Load(Dictionary<string, object> dict)
    {
        base.Load(dict);
        if (dict.ContainsKey(nameof(LutData)))
        {
            var base64Data = dict[nameof(LutData)].ToString();
            var bytes = Convert.FromBase64String(base64Data);
            using var ms = new MemoryStream(bytes);
            using var br = new BinaryReader(ms);
            LutData.Deserialize(br);
        }
    }
}