using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using InABox.Core;

namespace InABox.DynamicGrid
{
    public abstract class BaseDynamicGrid : ContentControl
    {
        public static readonly DependencyProperty UseWaitCursorProperty =
            DependencyProperty.Register(nameof(UseWaitCursor), typeof(bool), typeof(BaseDynamicGrid));

        protected enum ClipAction
        {
            Cut,
            Copy
        }

        public BaseDynamicGrid()
        {
            UseWaitCursor = true;
        }

        public bool UseWaitCursor
        {
            get => (bool)GetValue(UseWaitCursorProperty);
            set => SetValue(UseWaitCursorProperty, value);
        }
        
        public static Brush SelectionBackground { get; set; }

        public static Brush SelectionForeground { get; set; }

        public static Brush FilterBackground { get; set; }

        static BaseDynamicGrid()
        {
            SelectionForeground = new SolidColorBrush(Colors.Black);
            SelectionBackground = new SolidColorBrush(Colors.Silver);
            FilterBackground = new SolidColorBrush(Color.FromArgb(0xFF, 0xE9, 0xF7, 0xC9));
        }
    }

    public abstract class BaseDynamicGrid<T> : BaseDynamicGrid, IDynamicGrid where T : BaseObject, new()
    {
        public delegate void EntitySaveEvent(IDynamicEditorForm editor, T[] items);

        public delegate void ValidateEvent(object sender, T[] items, List<string> errors);

        public EntitySaveEvent? OnAfterSave;
        public EntitySaveEvent? OnBeforeSave;
        public event OnPrintData? OnPrintData;
        public event OnAfterReloadEventHandler? OnAfterReload;
        
        public event OnDefineFilter? OnDefineFilter;
        public abstract event OnFilterRecord? OnFilterRecord;
        public event OnCreateItem? OnCreateItem;
        public abstract event OnCustomiseEditor<T>? OnCustomiseEditor;
        public virtual event OnCustomiseColumns? OnCustomiseColumns;
        public abstract event OnDoubleClick? OnDoubleClick;

        public OnGetDynamicGridStyle? OnGetStyle { get; set; }

        public ValidateEvent? OnValidate;
        protected DynamicGridStyleSelector<T> StyleSelector;

        public BaseDynamicGrid()
        {
            Options = new FluentList<DynamicGridOption>();
            Options.OnChanged += OptionsChanged;
            StyleSelector = GetStyleSelector();
            StyleSelector.GetStyle += (row, style) => GetStyle(row, style);
            HiddenColumns = new List<Expression<Func<T, object?>>>();
        }

        public List<Expression<Func<T, object?>>> HiddenColumns { get; }

        public void InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false)
        {
            InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
        }
        public virtual bool EditItems(object[] items, Func<Type, CoreTable>? PageDataHandler = null, bool PreloadPages = false)
        {
            var values = items.Select(x => (T)x).ToArray();
            return EditItems(values, PageDataHandler, PreloadPages);
        }

        //public abstract bool DirectEdit(CoreTable data);

        public FluentList<DynamicGridOption> Options { get; }
        public DynamicGridColumns MasterColumns { get; protected set; }
        public DynamicGridColumns VisibleColumns { get; protected set; }
        public CoreTable Data { get; set; }

        public virtual void ConfigureColumns(DynamicGridColumns columns)
        {
            OnCustomiseColumns?.Invoke(this, columns);
        }

        public abstract CoreRow[] SelectedRows { get; set; }

        public abstract void AddVisualFilter(string column, string value);

        public abstract Button AddButton(string caption, BitmapImage? image, string? tooltip, Func<Button, CoreRow[], bool> action,
            DynamicGridButtonPosition position = DynamicGridButtonPosition.Left);
        
        public virtual double RowHeight { get; set; }
        public virtual double HeaderHeight { get; set; }
        public new virtual double FontSize { get; set; }

        public void AddHiddenColumn(string column)
        {
            var expression = CoreUtils.CreateLambdaExpression<T>(column);
            HiddenColumns.Add(expression);
        }

        public abstract int DesiredWidth();

        public abstract void Refresh(bool reloadcolumns, bool reloaddata);

        public abstract void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true);
        public abstract void UpdateRow<T, TType>(CoreRow row, Expression<Func<T, TType>> column, TType value, bool refresh = true);
        protected abstract DynamicGridStyleSelector<T> GetStyleSelector();

        protected virtual DynamicGridStyle GetStyle(CoreRow row, DynamicGridStyle style)
        {
            return OnGetStyle != null ? OnGetStyle(row, style) : style;
        }

        public abstract void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable>? pageDataHandler = null, bool preloadPages = false);
        public abstract bool EditItems(T[] items, Func<Type, CoreTable>? PageDataHandler = null, bool PreloadPages = false);

        public Filter<T>? DefineFilter()
        {
            if (OnDefineFilter is null)
                return null;
            var result = OnDefineFilter.Invoke(this, typeof(T)) as Filter<T>;
            return result;
        }

        protected virtual T CreateItem()
        {
            var result = new T();
            OnCreateItem?.Invoke(this, result);
            return result;
        }

        protected virtual void DoPrint(object sender)
        {
            OnPrintData?.Invoke(sender);
        }

        protected abstract void OptionsChanged(object sender, EventArgs args);

        protected virtual void AfterReload()
        {
        }

        protected void DoAfterReload()
        {
            AfterReload();
            OnAfterReload?.Invoke(this);
        }

        public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
        {
            var result = selection == Selection.None
                ? new TType[] { }
                : selection == Selection.Selected
                    ? SelectedRows.Select(r => r.Get(column)).ToArray()
                    : Data.ExtractValues(column);
            return result;
        }
    }
}