using InABox.Core;
using InABox.WPF;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;

namespace InABox.DynamicGrid
{
    public class DFMultiImageControl : DynamicFormFieldControl<DFLayoutMultiImage, DFLayoutMultiImageProperties, List<byte[]>>
    {
        private Grid Grid = null!; // Late-initialised
        private StackPanel Images = null!; // Late-initialised
        private bool Enabled = true;

        static DFMultiImageControl()
        {
            IsEnabledProperty.OverrideMetadata(
                typeof(DFMultiImageControl),
                new UIPropertyMetadata(
                    true,
                    ControlIsEnabledChanged));
        }

        private static void ControlIsEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var control = (DFMultiImageControl)obj;
            control.IsEnabled = true;
            control.Enabled = (bool)e.NewValue;
        }

        protected override FrameworkElement Create()
        {
            Grid = new Grid();
            Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            Grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            Grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            Grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            var imagesScroll = new ScrollViewer
            {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                VerticalScrollBarVisibility = ScrollBarVisibility.Disabled,
                Background = new SolidColorBrush(Colors.Gray)
            };

            Images = new StackPanel { Orientation = Orientation.Horizontal, Height = 200 };

            imagesScroll.Content = Images;

            var clearButton = new Button
            {
                Content = "Clear",
                Margin = new Thickness(0, 5, 0, 0),
                Width = 60,
                Height = 35
            };
            clearButton.Click += MultiImageClear_Click;

            var addButton = new Button
            {
                Content = "Add",
                Margin = new Thickness(0, 5, 0, 0),
                Width = 60,
                Height = 35
            };
            addButton.Click += MultiImageAdd_Click;

            imagesScroll.SetGridPosition(0, 0, 1, 3);
            clearButton.SetGridPosition(1, 0, 1, 1);
            addButton.SetGridPosition(1, 2, 1, 1);
            Grid.Children.Add(imagesScroll);
            Grid.Children.Add(clearButton);
            Grid.Children.Add(addButton);

            return Grid;
        }
        private void AddMultiImage(byte[] data)
        {
            var border = new Border
            {
                Effect = new DropShadowEffect
                {
                    ShadowDepth = 0,
                    BlurRadius = 10
                }
            };

            var image = new Image
            {
                Margin = new Thickness(5)
            };
            var source = ImageUtils.BitmapImageFromBytes(data);
            if (source != null)
            {
                image.Source = source;

                var menu = new ContextMenu();
                menu.AddItem("View Image", null, image, MultiImageView_Click);
                menu.AddItem("Remove Image", null, border, MultiImageRemove_Click);
                image.ContextMenu = menu;
                image.ContextMenuOpening += (sender, args) =>
                {
                    if (!Enabled) args.Handled = true;
                };

                border.Child = image;
                Images.Children.Add(border);
            }
        }

        private void MultiImageClear_Click(object sender, RoutedEventArgs e)
        {
            if (Images.Children.Count > 0)
            {
                Images.Children.Clear();
                ChangeField();
            }
        }

        private void MultiImageView_Click(Image element)
        {
            var filename = Path.ChangeExtension(Path.GetTempFileName(), ".jpg");
            File.WriteAllBytes(filename, EmbeddedImageUtilities.SaveImageToBytes(element, false, new JpegBitmapEncoder()) ?? Array.Empty<byte>());

            var gsProcessInfo = new ProcessStartInfo();
            gsProcessInfo.Verb = "open";
            gsProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
            gsProcessInfo.FileName = filename;
            gsProcessInfo.UseShellExecute = true;
            Process.Start(gsProcessInfo);
        }
        private void MultiImageRemove_Click(FrameworkElement element)
        {
            Images.Children.Remove(element);
            ChangeField();
        }
        private void MultiImageAdd_Click(object sender, RoutedEventArgs e)
        {
            if (EmbeddedImageUtilities.SelectImageFile(out var data))
            {
                AddMultiImage(data);
                ChangeField();
            }
        }

        public override List<byte[]> GetValue()
        {
            var data = new List<byte[]>();
            foreach (var image in Images.FindVisualChildren<Image>())
            {
                var imgData = EmbeddedImageUtilities.SaveImageToBytes(image, false, new JpegBitmapEncoder());
                if (imgData != null)
                {
                    data.Add(imgData);
                }
            }

            return data;
        }

        public override void SetValue(List<byte[]>? value)
        {
            Images.Children.Clear();

            if (value is IEnumerable<byte[]> data)
            {
                foreach (var imgData in data)
                {
                    AddMultiImage(imgData);
                }
            }
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == IsEnabledProperty)
            {
                Grid.RowDefinitions[1].Height = (bool)e.NewValue
                    ? GridLength.Auto
                    : new GridLength(0);
            }
        }
        protected override bool IsEmpty() => Images.Children.Count == 0;
    }
}
