using MaterialSkin.Controls;
using OpenCvSharp.XImgProc;
using System.Text.RegularExpressions;
using MaterialSkin.Core.Controls;
using OpenCvSharp.Extensions;
using VisionBuilder.UI.Common.ViewModel;
using VisionBuilder.UI.Common.ViewModel.Classes;
using VisionBuilder.UI.Common.ViewModel.Interfaces.UI;

namespace VisionBuilder.UI.Windows.Dialogs
{
    public partial class RecipeSelectionDialog : MaterialForm
    {
        private readonly RecipeSelectionVM _recipeSelectionVm;
        private readonly IRecipeCreationTool _recipeCreationTool;

        public RecipeSelectionDialog(RecipeSelectionVM recipeSelectionVm, IRecipeCreationTool recipeCreationTool)
        {
            _recipeSelectionVm = recipeSelectionVm;
            _recipeCreationTool = recipeCreationTool;

            InitializeComponent();
            ReloadRecipes();

            if (_recipeCreationTool.Enabled)
            {
                btnCreateNewRecipe.Visible = true;
            }
        }

        public void ReloadRecipes()
        {

            var recipes = _recipeSelectionVm.Recipes.ToList();
            listView1.Items.Clear();

            recipes = recipes.OrderBy(x => x.RecipeName).ToList();
            listView1.LargeImageList = new ImageList() { ColorDepth = ColorDepth.Depth24Bit };
            listView1.LargeImageList.ImageSize = new Size(128, 128);

            var plug = new Bitmap(128, 128);
            using (Graphics g = Graphics.FromImage(plug))
            {
                g.Clear(Color.Gray);
            }

            listView1.LargeImageList.Images.Add("plug", plug);




            recipes.ForEach(x =>
            {



                if (x.Image != null)
                {
                    var image = x.Image.Resize(new OpenCvSharp.Size(128, 128)).ToBitmap();
                    listView1.LargeImageList.Images.Add(x.RecipeName, image);
                    listView1.Items.Add(x.RecipeName, x.RecipeName, x.RecipeName).Tag = x;
                }
                else
                {
                    listView1.Items.Add(x.RecipeName, x.RecipeName, "plug").Tag = x;
                }

            });

        }
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedIndices.Count > 0)
            {
                _recipeSelectionVm.SelectedRecipe = (RecipeData)listView1.SelectedItems[0].Tag!;
            }
            DialogResult = DialogResult.OK;
        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private async void btnCreateNewRecipe_Click(object sender, EventArgs e)
        {
            var recipeName = await _recipeCreationTool.CreateRecipeAsync();
            if (recipeName != null)
            {
                _recipeSelectionVm.SelectedRecipe = new RecipeData() { RecipeName = recipeName };
                DialogResult = DialogResult.OK;
            }
        }
    }
}
