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.DynamicGrid.Properties;
using InABox.Wpf;
using InABox.WPF;
using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;

namespace InABox.DynamicGrid
{
    public delegate BaseEditor? DefineEditorEventHandler(object item, DynamicGridColumn column);

    public delegate void DynamicGridSaveEvent(object sender, CancelEventArgs args);

    public interface IDynamicEditorForm
    {
        public delegate Document? FindDocumentEvent(string FileName);
        public delegate Document? GetDocumentEvent(Guid id);
        public delegate void SaveDocumentEvent(Document document);

        public event OnValidateData? OnValidateData;

        public event OnCustomiseColumns? OnCustomiseColumns;
        public event OnDefineFilter? OnDefineFilter;

        public event OnDefineLookup? OnDefineLookups;
        public event OnLookupsDefined? OnLookupsDefined;

        public event DefineEditorEventHandler? OnDefineEditor;
        public event OnFormCustomiseEditor? OnFormCustomiseEditor;
        public event OnReconfigureEditors? OnReconfigureEditors;

        public event OnAfterEditorValueChanged? OnAfterEditorValueChanged;
        public event EditorValueChangedHandler? OnEditorValueChanged;

        public event GetDocumentEvent? OnGetDocument;
        public event FindDocumentEvent? OnFindDocument;
        public event SaveDocumentEvent? OnSaveDocument;

        public event OnSelectPage? OnSelectPage;

        public event DynamicGridSaveEvent? OnSaveItem;


        DynamicEditorPages? Pages { get; }

        bool ReadOnly { get; set; }

        BaseObject[] Items { get; set; }

        void Setup(Type type, DynamicEditorPages? pages = null, DynamicEditorButtons? buttons = null,
            Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false);

        IDynamicEditorControl FindEditor(string columnName);

        void UnloadEditorPages(bool saved);
    }

    public class UtilityItem
    {
        public string Name { get; set; }
        public ImageSource Icon { get; set; }
        public string Text { get; set; }
        public SizeMode Mode { get; set; }
        public ICommand Command { get; set; }
    }

    public class UtilityViewModel
    {
        /// <summary>
        ///     Constructor of the UtilityViewModel class.
        /// </summary>
        public UtilityViewModel()
        {
            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://prs-software.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 OnValidateData? OnValidateData { add => Form.OnValidateData += value; remove => Form.OnValidateData -= value; }

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

        public event OnDefineLookup? OnDefineLookups { add => Form.OnDefineLookups += value; remove => Form.OnDefineLookups -= value; }
        public event OnLookupsDefined? OnLookupsDefined { add => Form.OnLookupsDefined += value; remove => Form.OnLookupsDefined -= value; }

        public event DefineEditorEventHandler? OnDefineEditor { add => Form.OnDefineEditor += value; remove => Form.OnDefineEditor -= value; }
        public event OnFormCustomiseEditor? OnFormCustomiseEditor { add => Form.OnFormCustomiseEditor += value; remove => Form.OnFormCustomiseEditor -= value; }
        public event OnReconfigureEditors? OnReconfigureEditors { add => Form.OnReconfigureEditors += value; remove => 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 event IDynamicEditorForm.GetDocumentEvent? OnGetDocument { add => Form.OnGetDocument += value; remove => Form.OnGetDocument -= value; }
        public event IDynamicEditorForm.FindDocumentEvent? OnFindDocument { add => Form.OnFindDocument += value; remove => Form.OnFindDocument -= value; }
        public event IDynamicEditorForm.SaveDocumentEvent? OnSaveDocument { add => Form.OnSaveDocument += value; remove => Form.OnSaveDocument -= value; }

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

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


        public IDynamicEditorControl FindEditor(string columnName) => Form.FindEditor(columnName);

        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;
        }

        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);
        }

        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 + spareheight;
            var desiredwidth = width + sparewidth;
            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;
                }

            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();
            if (Form.Editor.IsCustomLayout)
                Title += "*";
        }

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

        #region Win32 API Stuff

        // Define the Win32 API methods we are going to use
        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        private static extern bool InsertMenu(IntPtr hMenu, int wPosition, int wFlags, int wIDNewItem, string lpNewItem);

        /// Define our Constants we will use
        public const int WM_SYSCOMMAND = 0x112;

        public const int MF_SEPARATOR = 0x800;
        public const int MF_BYPOSITION = 0x400;
        public const int MF_STRING = 0x0;

        public const int _EditLayoutID = 1000;
        public const int _ResetLayoutID = 1001;

        public IntPtr Handle => new WindowInteropHelper(this).Handle;

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Check if a System Command has been executed
            if (msg == WM_SYSCOMMAND)
                // Execute the appropriate code for the System Menu item that was clicked
                switch (wParam.ToInt32())
                {
                    case _EditLayoutID:
                        Form.EditLayout();
                        handled = true;
                        break;
                    case _ResetLayoutID:
                        if (MessageBox.Show(
                                "WARNING: This will delete any customisations you have made!\n\nAre you sure you wish to reset this layout?",
                                "Confirm Layout Reset", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            Form.ResetLayout();
                        handled = true;
                        break;
                }

            return IntPtr.Zero;
        }

        private void ConfigureSystemMenu(object sender, RoutedEventArgs e)
        {
            /// Get the Handle for the Forms System Menu
            var systemMenuHandle = GetSystemMenu(Handle, false);

            /// Create our new System Menu items just before the Close menu item
            InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty); // <-- Add a menu seperator
            InsertMenu(systemMenuHandle, 6, MF_BYPOSITION, _EditLayoutID, "Edit Layout");
            InsertMenu(systemMenuHandle, 7, MF_BYPOSITION, _ResetLayoutID, "Reset Layout");

            // Attach our WndProc handler to this Window
            var source = HwndSource.FromHwnd(Handle);
            source.AddHook(WndProc);
        }

        #endregion

        //private void Wiki_Click(object sender, RoutedEventArgs e)
        //{
        //    System.Diagnostics.Process.Start("https://prs-software.com.au/wiki/index.php/" + CurrentPanelSlug());
        //}

        //private string CurrentPanelSlug()
        //{
        //    if ((Items != null) && Items.Any())
        //        return Items.First().GetType().EntityName().Split('.').Last();
        //    return "";
        //}
    }
}