using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using InABox.Core;
using InABox.Wpf;
using InABox.WPF;
using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;

namespace InABox.DynamicGrid
{
    
    public class DynamicEditorFormModel
    {
        /// <summary>
        ///     Constructor of the UtilityViewModel class.
        /// </summary>
        public DynamicEditorFormModel()
        {
            var utilities = new ObservableCollection<UtilityItem>();
            utilities.Add(new UtilityItem
                { Name = "Help", Icon = Resources.help.AsBitmapImage(), Text = "", Mode = SizeMode.Normal, Command = HelpCommand });
            Utilities = utilities;
        }

        /// <summary>
        ///     Collection containing the complete details of the items to be bound in the title bar.
        /// </summary>
        public ObservableCollection<UtilityItem> Utilities { get; }

        /// <summary>
        ///     Commmand for the Help button.
        /// </summary>
        public DelegateCommand HelpCommand => new(HelpCommandAction);

        public static string Slug { get; set; }

        /// <summary>
        ///     Action that is performed when clicking the help button.
        /// </summary>
        private void HelpCommandAction(object param)
        {
            Process.Start("https://prsdigital.com.au/wiki/index.php/" + Slug);
        }
    }

    /// <summary>
    ///     Interaction logic for DynamicEditor.xaml
    /// </summary>
    public partial class DynamicEditorForm : ThemableChromelessWindow, IDynamicEditorForm
    {
        #region IDynamicEditorForm

        public bool ReadOnly { get => Form.ReadOnly; set => Form.ReadOnly = value; }
        public BaseObject[] Items { get => Form.Items; set => Form.Items = value; }
        public DynamicEditorPages? Pages { get => Form.Pages; }

        public event OnBeforeLoad? OnBeforeLoad;
        public void BeforeLoad() => OnBeforeLoad?.Invoke(this);

        public event OnAfterLoad? OnAfterLoad;
        public void AfterLoad() => OnAfterLoad?.Invoke(this);

        public event OnValidateData? OnValidateData { add => Form.OnValidateData += value; remove => Form.OnValidateData -= value; }

        public OnCustomiseColumns? OnCustomiseColumns { get => Form.OnCustomiseColumns; set { Form.OnCustomiseColumns = value; } }
        public OnDefineFilter? OnDefineFilter { get => Form.OnDefineFilter; set { Form.OnDefineFilter = value; } }

        public OnDefineLookup? OnDefineLookups { get => Form.OnDefineLookups; set { Form.OnDefineLookups = value; } }

        public DefineEditorEventHandler? OnDefineEditor { get => Form.OnDefineEditor; set { Form.OnDefineEditor = value; } }
        public event OnFormCustomiseEditor? OnFormCustomiseEditor;
        public OnReconfigureEditors? OnReconfigureEditors { get => Form.OnReconfigureEditors; set { Form.OnReconfigureEditors = value; } }
        
        public event OnAfterEditorValueChanged? OnAfterEditorValueChanged { add => Form.OnAfterEditorValueChanged += value; remove => Form.OnAfterEditorValueChanged -= value; }
        public event EditorValueChangedHandler? OnEditorValueChanged { add => Form.OnEditorValueChanged += value; remove => Form.OnEditorValueChanged -= value; }

        public IDynamicEditorForm.GetDocumentEvent? OnGetDocument { get => Form.OnGetDocument; set { Form.OnGetDocument = value; } }
        public IDynamicEditorForm.FindDocumentEvent? OnFindDocument { get => Form.OnFindDocument; set { Form.OnFindDocument = value; } }
        public IDynamicEditorForm.SaveDocumentEvent? OnSaveDocument { get => Form.OnSaveDocument; set { Form.OnSaveDocument = value; } }

        public event OnSelectPage? OnSelectPage { add => Form.OnSelectPage += value; remove => Form.OnSelectPage -= value; }

        public DynamicGridSaveEvent? OnSaveItem { get => Form.OnSaveItem; set { Form.OnSaveItem = value; } }


        public IDynamicEditorControl FindEditor(string columnName) => Form.FindEditor(columnName);
        public object? GetEditorValue(string columnName) => Form.GetEditorValue(columnName);
        public void SetEditorValue(string columnName, object? value) => Form.SetEditorValue(columnName, value);

        public void UnloadEditorPages(bool saved) => Form.UnloadEditorPages(saved);

        #endregion

        public DynamicEditorForm()
        {
            InitializeComponent();
            
            //this.Loaded += new RoutedEventHandler(ConfigureSystemMenu);

            Form.OnEditorCreated += Editor_OnEditorCreated;
            Form.OnOK += Form_OnOK;
            Form.OnCancel += Form_OnCancel;
            Form.OnFormCustomiseEditor += (sender, items, column, editor) => OnFormCustomiseEditor?.Invoke(sender, items, column, editor);
        }

        public DynamicEditorForm(Type type, DynamicEditorPages? pages = null, DynamicEditorButtons? buttons = null,
            Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false): this()
        {
            Setup(type, pages, buttons, pageDataHandler, preloadPages);
        }

        public void Setup(Type type, DynamicEditorPages? pages = null, DynamicEditorButtons? buttons = null,
            Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false)
        {
            Form.Setup(type, pages, buttons, pageDataHandler, preloadPages);
        }
        public void SetLayoutType<T>() where T : DynamicEditorGridLayout => Form.SetLayoutType<T>();

        private void Form_OnCancel()
        {
            DialogResult = false;
        }

        private void Form_OnOK()
        {
            DialogResult = true;
        }

        private void Editor_OnEditorCreated(object sender, double height, double width)
        {
            var screen = WpfScreen.GetScreenFrom(new Point(Left, Top));

            double spareheight = 90;
            double sparewidth = 25;

            var desiredheight = height;
            var desiredwidth = width;
            if (Form.Pages != null)
                foreach (var page in Form.Pages)
                {
                    if (desiredheight < page.MinimumSize().Height)
                        desiredheight = page.MinimumSize().Height;
                    if (desiredwidth < page.MinimumSize().Width)
                        desiredwidth = page.MinimumSize().Width;
                }

            desiredheight += spareheight;
            desiredwidth += sparewidth;

            var maxheight = screen.WorkingArea.Height - 0;
            Height = desiredheight > maxheight ? maxheight : desiredheight;

            var maxwidth = screen.WorkingArea.Width - 0;
            Width = desiredwidth > maxwidth ? maxwidth : desiredwidth;

            Left = screen.DeviceBounds.Left + (screen.DeviceBounds.Width - Width) / 2.0F;
            Top = screen.DeviceBounds.Top + (screen.DeviceBounds.Height - Height) / 2.0F;

            var scaption = Form.Items[0].GetType().GetCaption();
            Title = "Edit " + scaption.SplitCamelCase();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (DialogResult == true)
                Form.SaveItem(e);
        }
    }
}