using OpenCvSharp;
using OpenCvSharp.Extensions;
using VisionBuilder.UI.Common.ViewModel;

namespace VisionBuilder.UI.Windows.Components;

public class PreviewWindow:PictureBox
{
    private PreviewVM _previewVm;

    public void SetViewModel(PreviewVM previewVm)
    {
        _previewVm = previewVm;
        _previewVm.PropertyChanged += _previewVm_PropertyChanged;
    }

    private void _previewVm_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case nameof(PreviewVM.ImagePreview):
                var tmp = _previewVm.ImagePreview?.ToBitmap();
                var bmp = new Bitmap(_previewVm.ImagePreview?.Width ?? 0, _previewVm.ImagePreview?.Height ?? 0);
                // hack to avoid IDS image glitch
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.Clear(Color.Pink);
                    g.DrawImage(tmp,0,0);
                }

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    // draw red border around the image if it's an error
                    if (_previewVm.IsError)
                    {
                        using (Pen pen = new Pen(Color.Red, 5))
                        {
                            g.DrawRectangle(pen, 0, 0, bmp.Width - 1, bmp.Height - 1);
                        }
                    }
                }
                Image = bmp;
                Invalidate();
                break;

        }
       
    }

    public PreviewWindow()
    {
        SizeMode = PictureBoxSizeMode.Zoom;
    }
}