using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup.Localizer;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using InABox.Clients;
using InABox.Core;
using InABox.WPF;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Brush = System.Windows.Media.Brush;
using Color = System.Drawing.Color;
using Image = System.Windows.Controls.Image;
using Point = System.Windows.Point;
using PointI = System.Drawing.Point;
using Rectangle = System.Windows.Shapes.Rectangle;

namespace InABox.DynamicGrid;

public class DynamicFormCreateElementArgs : EventArgs
{
    public DynamicFormCreateElementArgs(DFLayoutElement element, string name)
    {
        Element = element;
        Name = name;
    }

    public DFLayoutElement Element { get; }

    public string Name { get; }
}

public delegate FrameworkElement DynamicFormCreateElementDelegate(object sender, DynamicFormCreateElementArgs e);

public delegate void DynamicFormAfterDesignDelegate(object sender);

public delegate void DynamicFormAfterRenderDelegate(DynamicFormDesignGrid sender);

public delegate void DynamicFormOnChangedDelegate(DynamicFormDesignGrid sender, string fieldName);

public enum FormMode
{
    /// <summary>
    /// The form is read-only.
    /// </summary>
    ReadOnly,
    /// <summary>
    /// Standard option for when the form is being filled in by the associated employee.
    /// </summary>
    Filling,
    /// <summary>
    /// Standard option for when the form is being previewed - that is, it is acting with placeholder values that will not get saved.
    /// It is still editable.
    /// </summary>
    Preview,
    /// <summary>
    /// Once the form has been completed, or the person editing is not the employee the form applies to, then they are put in Editing Mode.<br/>
    /// This is only possible if <see cref="CanEditCompletedForms"/> is enabled.
    /// </summary>
    Editing,
    /// <summary>
    /// The form layout is being designed
    /// </summary>
    Designing
}

public class DynamicFormDesignGrid : Grid, IDFRenderer
{
    //private bool _designing;

    public bool GridInitialized { get; private set; } = false;

    //private bool _readonly;


    private readonly SolidColorBrush BackgroundBrush = new(Colors.WhiteSmoke);
    private readonly SolidColorBrush BorderBrush = new(Colors.Silver);

    private readonly Dictionary<Type, IDynamicGrid> elementgrids = new();

    private readonly Dictionary<DFLayoutControl, FrameworkElement> elementmap = new();
    private readonly Dictionary<DFLayoutControl, Border> borderMap = new();
    private readonly SolidColorBrush FieldBrush = new(Colors.LightYellow);


    private readonly SolidColorBrush RequiredFieldBrush = new(Colors.Orange);

    public DynamicFormDesignGrid()
    {
        PreviewMouseLeftButtonDown += Grid_PreviewMouseLeftButtonDown;
        PreviewMouseMove += Grid_PreviewMouseMove;
        PreviewMouseLeftButtonUp += Grid_PreviewMouseLeftButtonUp;
    }

    #region Backing Properties

    private readonly List<DynamicFormElement> _elements = new();
    private readonly List<DynamicFormElementAction> _elementActions = new();
    private bool _showBorders = true;
    private IDigitalFormDataModel? _datamodel;
    private DFLayout form = new();
    private FormMode _mode;
    private IList<DigitalFormVariable> _variables = new List<DigitalFormVariable>();
    private bool _isChanged;
    private bool _changing = false;

    #endregion

    #region Public Properties

    public bool ShowBorders
    {
        get => _showBorders || _mode == FormMode.Designing;
        set
        {
            _showBorders = value;
            CheckRefresh();
        }
    }

    public IDigitalFormDataModel? DataModel
    {
        get => _datamodel;
        set
        {
            _datamodel = value;
            if(_datamodel != null)
            {
                var task = Task.Run(() =>
                {
                    var waiting = true;
                    _datamodel.Load(m => { waiting = false; });
                    while (waiting) ;
                });
                task.Wait();
            }

            CheckRefresh();
        }
    }

    public DFLayout Form
    {
        get => form;
        set
        {
            form = value;
            form.Renderer = this;

            CheckRefresh();
        }
    }

    public FormMode Mode
    {
        get => _mode;
        set
        {
            if (_mode != value)
            {
                var oldMode = _mode;
                if (_mode == FormMode.Designing)
                {
                    OnAfterDesign?.Invoke(this);
                }

                _mode = value;

                CheckRefresh(oldMode != FormMode.Designing);
            }
        }
    }

    public bool IsDesigning { get => _mode == FormMode.Designing; }
    public bool IsReadOnly { get => _mode == FormMode.ReadOnly; }
    public bool IsEditing { get => _mode == FormMode.Editing || _mode == FormMode.Filling; }
    public bool IsChanged => _isChanged;

    public delegate DigitalFormVariable? CreateVariableHandler(Type fieldType);
    public delegate bool EditVariableHandler(DigitalFormVariable variable);

    public event CreateVariableHandler? OnCreateVariable;
    public event EditVariableHandler? OnEditVariable;

    public delegate void CustomiseElementContextMenuHandler(ContextMenu menu, DFLayoutElement element);
    public event CustomiseElementContextMenuHandler? CustomiseElementContextMenu;

    public IList<DigitalFormVariable> Variables
    {
        get => _variables;
        set
        {
            _variables = value;
            CheckRefresh();
        }
    }

    #endregion

    #region Events

    public event DynamicFormAfterDesignDelegate? OnAfterDesign;

    public event DynamicFormCreateElementDelegate? OnCreateElement;

    public event DynamicFormAfterRenderDelegate? OnAfterRender;

    public event DynamicFormOnChangedDelegate? OnChanged;

    #endregion

    #region Rows

    class RowData
    {
        public string RowHeight { get; set; }

        public RowData(string rowHeight)
        {
            RowHeight = rowHeight;
        }
    }

    internal void CollapseRows(FormHeader header, bool collapsed)
    {
        var startRow = this.GetRow(header) + this.GetRowSpan(header);

        var nextRow = elementmap
            .Where(x => x.Value is DFHeaderControl headerControl && headerControl.Header != header)
            .Select(x => this.GetRow(x.Value))
            .Where(x => x >= startRow).DefaultIfEmpty(-1).Min();

        if (nextRow == -1)
        {
            nextRow = RowDefinitions.Count;
        }

        for (int row = startRow; row < nextRow; ++row)
        {
            var rowDefinition = RowDefinitions[row];
            if(rowDefinition.Tag is not RowData rowData)
            {
                throw new Exception("Row definition tag is not RowData");
            }

            if (collapsed)
            {
                rowDefinition.Height = new GridLength(0);
            }
            else
            {
                rowDefinition.Height = StringToGridLength(rowData.RowHeight);
            }
        }
    }

    #endregion

    #region Elements

    class DynamicFormElement
    {
        public string Caption { get; set; }
        public Type ElementType { get; set; }
        public string Category { get; set; }
        public bool AllowDuplicate { get; set; }
        public object? Tag { get; set; }
        public Func<object?, DFLayoutElement>? CreateElement { get; set; }

        public bool Visible { get; set; }

        public DynamicFormElement(string caption, Type elementType, string category, bool allowDuplicate, bool visible, object? tag, Func<object?, DFLayoutElement>? createElement)
        {
            Caption = caption;
            ElementType = elementType;
            Category = category;
            AllowDuplicate = allowDuplicate;
            Tag = tag;
            CreateElement = createElement;
            Visible = visible;
        }
    }

    class DynamicFormElementAction
    {
        public string Caption { get; set; }

        public Bitmap? Image { get; set; }

        public string Category { get; set; }

        public object? Tag { get; set; }

        public Func<object?, DFLayoutElement?> OnClick { get; set; }

        public DynamicFormElementAction(string caption, Bitmap? image, string category, object? tag, Func<object?, DFLayoutElement> onClick)
        {
            Caption = caption;
            Image = image;
            Category = category;
            Tag = tag;
            OnClick = onClick;
        }
    }

    public void ClearElementTypesAndActions()
    {
        _elements.Clear();
        _elementActions.Clear();
    }

    public void AddElementType<TElement>(string caption, string category, bool allowduplicate = false, bool visible = true)
        where TElement : DFLayoutElement
    {
        AddElementType(typeof(TElement), caption, category, allowduplicate, visible: visible);
    }
    public void AddElementType<TElement, TTag>(string caption, string category, TTag tag, Func<TTag, TElement> createElement, bool allowduplicate = false, bool visible = true)
        where TElement : DFLayoutElement
    {
        AddElementType(typeof(TElement), caption, category, tag, createElement, allowduplicate, visible: visible);
    }

    public void AddElementType(Type TElement, string caption, string category, bool allowduplicate = false, bool visible = true)
    {
        _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, null, null));
    }

    public void AddElementType<TTag>(Type TElement, string caption, string category, TTag tag, Func<TTag, DFLayoutElement> createElement, bool allowduplicate = false, bool visible = true)
    {
        _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, tag, x => createElement((TTag)x)));
    }

    public void AddElementAction<TTag>(string caption, Bitmap? image, string category, TTag tag, Func<TTag, DFLayoutElement?> onClick)
    {
        _elementActions.Add(new(caption, image, category, tag, x => onClick((TTag)x)));
    }

    internal FrameworkElement? CreateElement(DFLayoutElement element)
    {
        var elementType = element.GetType();
        if(_elements.FirstOrDefault(x => x.ElementType == elementType) is DynamicFormElement el)
        {
            return OnCreateElement?.Invoke(this, new DynamicFormCreateElementArgs(element, el.Caption));
        }
        return null;
    }

    #endregion

    #region Utilities

    private static VerticalAlignment GetVerticalAlignment(DFLayoutAlignment alignment)
    {
        return alignment == DFLayoutAlignment.Start
            ? VerticalAlignment.Top
            : alignment == DFLayoutAlignment.End
                ? VerticalAlignment.Bottom
                : alignment == DFLayoutAlignment.Middle
                    ? VerticalAlignment.Center
                    : VerticalAlignment.Stretch;
    }

    private static HorizontalAlignment GetHorizontalAlignment(DFLayoutAlignment alignment)
    {
        return alignment == DFLayoutAlignment.Start
            ? HorizontalAlignment.Left
            : alignment == DFLayoutAlignment.End
                ? HorizontalAlignment.Right
                : alignment == DFLayoutAlignment.Middle
                    ? HorizontalAlignment.Center
                    : HorizontalAlignment.Stretch;
    }

    private static GridLength StringToGridLength(string length)
    {
        if (string.IsNullOrWhiteSpace(length) || string.Equals(length.ToUpper(), "AUTO"))
            return new GridLength(1, GridUnitType.Auto);

        if (!double.TryParse(length.Replace("*", ""), out var value))
            value = 1.0F;
        var type = length.Contains('*') ? GridUnitType.Star : GridUnitType.Pixel;
        return new GridLength(value, type);
    }

    private static string GridLengthToString(GridLength length)
    {
        if (length.IsStar)
            return length.Value == 1.0F ? "*" : string.Format("{0}*", length.Value);
        if (length.IsAuto)
            return "Auto";
        return length.Value.ToString();
    }

    private static string FormatGridLength(GridLength length, IEnumerable<GridLength> others)
    {
        if (length.IsStar)
        {
            double total = 0.0F;
            foreach (var other in others.Where(x => x.IsStar))
                total += other.Value;
            return string.Format("{0:F0}%", total != 0 ? length.Value * 100.0F / total : 0);
        }

        if (length.IsAuto)
            return "Auto";
        return string.Format("{0}px", length.Value);
    }

    private static void AddClick<TTag>(ButtonBase button, TTag tag, Action<TTag> click)
    {
        button.Tag = tag;
        button.Click += (o, e) => click((TTag)(o as FrameworkElement)!.Tag);
    }

    #endregion

    #region Design Mode

    #region Selection

    private class CellSelection : Border
    {
        private static readonly System.Windows.Media.Color MainSelectionBorder = Colors.LightBlue;

        private int startRow;
        private int endRow;
        private int startColumn;
        private int endColumn;

        public int StartRow
        {
            get => startRow;
            set
            {
                startRow = value;
                UpdatePosition();
            }
        }

        public int StartColumn
        {
            get => startColumn;
            set
            {
                startColumn = value;
                UpdatePosition();
            }
        }

        public int EndRow
        {
            get => endRow;
            set
            {
                endRow = value;
                UpdatePosition();
            }
        }

        public int EndColumn
        {
            get => endColumn;
            set
            {
                endColumn = value;
                UpdatePosition();
            }
        }

        public bool Selecting = true;

        public enum SelectionTypes
        {
            Main,
            Secondary,
            Resizable,
            ResizeBackground
        }

        public SelectionTypes SelectionType;

        public enum Direction
        {
            None,
            Left,
            Right,
            Top,
            Bottom,
            All
        }
        public Direction DragDirection;
        public bool IsDragging => DragDirection != Direction.None;

        public bool IsRowSelection => StartColumn == 0;
        public bool IsColumnSelection => StartRow == 0;

        public CellSelection(int startRow, int startColumn, int endRow, int endColumn, SelectionTypes selectionType)
        {
            SelectionType = selectionType;
            switch (selectionType)
            {
                case SelectionTypes.Main:
                    InitialiseMain();
                    break;
                case SelectionTypes.Secondary:
                    InitialiseSecondary();
                    break;
                case SelectionTypes.Resizable:
                    InitializeResizable();
                    break;
                case SelectionTypes.ResizeBackground:
                    InitializeResizeBackground();
                    break;
            }

            this.startRow = startRow;
            this.startColumn = startColumn;
            this.endRow = endRow;
            this.endColumn = endColumn;
            UpdatePosition();
        }

        private void InitialiseMain()
        {
            var colour = MainSelectionBorder;
            BorderBrush = new SolidColorBrush(colour);
            Background = new SolidColorBrush(new System.Windows.Media.Color
            {
                A = (byte)(colour.A / 2),
                R = colour.R,
                G = colour.G,
                B = colour.B
            });
            SetZIndex(this, 2);
            BorderThickness = new Thickness(1);
        }

        private void InitialiseSecondary()
        {
            var rectangle = new Rectangle
            {
                StrokeDashArray = new DoubleCollection { 4, 4 },
                Stroke = new SolidColorBrush(Colors.Gray),
                StrokeThickness = 1.5
            };
            rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
            rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
            var brush = new VisualBrush { Visual = rectangle };

            BorderBrush = brush;
            BorderThickness = new Thickness(1.5);
            Margin = new Thickness(3);
        }

        private void InitializeResizable()
        {
            var rectangle = new Rectangle
            {
                StrokeDashArray = new DoubleCollection { 4, 4 },
                Stroke = new SolidColorBrush(Colors.Gray),
                StrokeThickness = 3
            };
            rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
            rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
            var brush = new VisualBrush { Visual = rectangle };

            BorderBrush = brush;

            Background = new SolidColorBrush(Colors.Transparent);
            SetZIndex(this, 2);
            BorderThickness = new Thickness(10);

            MouseMove += Resizable_MouseMove;
        }

        private void InitializeResizeBackground()
        {
            var colour = Colors.WhiteSmoke;
            Background = new SolidColorBrush(new System.Windows.Media.Color
            {
                A = (byte)(colour.A / 2),
                R = colour.R,
                G = colour.G,
                B = colour.B
            });
            SetZIndex(this, 1);
            BorderThickness = new Thickness(0);
        }

        public bool StartDragging(Point position)
        {
            if (!IsMouseDirectlyOver) return false;

            var dX = Math.Min(position.X, ActualWidth - position.X);
            var dY = Math.Min(position.Y, ActualHeight - position.Y);
            if(Math.Min(dX, dY) < 10)
            {
                if (dX < dY)
                {
                    DragDirection = position.X < ActualWidth / 2 ? Direction.Left : Direction.Right;
                }
                else
                {
                    DragDirection = position.Y < ActualHeight / 2 ? Direction.Top : Direction.Bottom;
                }
            }
            else
            {
                DragDirection = Direction.All;
                return false;
            }
            return true;
        }

        private void Resizable_MouseMove(object sender, MouseEventArgs e)
        {
            if (!IsMouseDirectlyOver || IsDragging) return;

            var position = e.GetPosition(this);

            var dX = Math.Min(position.X, ActualWidth - position.X);
            var dY = Math.Min(position.Y, ActualHeight - position.Y);
            if (Math.Min(dX, dY) < 10)
            {
                if (dX < dY)
                {
                    Cursor = Cursors.SizeWE;
                }
                else
                {
                    Cursor = Cursors.SizeNS;
                }
            }
            else
            {
                Cursor = Cursors.Arrow;
            }
        }

        public void SetEnd(int endRow, int endColumn)
        {
            this.endRow = endRow;
            this.endColumn = endColumn;
            UpdatePosition();
        }

        public void SetSize(int startRow, int startColumn, int endRow, int endColumn)
        {
            this.startRow = startRow;
            this.startColumn = startColumn;
            this.endRow = endRow;
            this.endColumn = endColumn;
            UpdatePosition();
        }

        private void UpdatePosition()
        {
            Grid.SetRow(this, Math.Min(startRow, endRow));
            Grid.SetRowSpan(this, Math.Abs(endRow - startRow) + 1);

            Grid.SetColumn(this, Math.Min(startColumn, endColumn));
            Grid.SetColumnSpan(this, Math.Abs(endColumn - startColumn) + 1);
        }

        public CellRange ToRange() => new CellRange(StartRow, StartColumn, EndRow, EndColumn);
    }

    private CellSelection? Selection;
    private Dictionary<DFLayoutControl, CellSelection> SelectedItemsSelections = new();

    private class Range
    {
        public int Start { get; set; }

        public int End { get; set; }

        public int Min => Math.Min(Start, End);
        public int Max => Math.Max(Start, End);

        public Range(int start, int end)
        {
            Start = start;
            End = end;
        }

        public override string ToString() => $"{Start} -> {End}";
    }
    
    private class CellRange
    {
        public int StartRow { get; set; }
        public int StartColumn { get; set; }
        public int EndRow { get; set; }
        public int EndColumn { get; set; }

        public int MinRow => Math.Min(StartRow, EndRow);
        public int MinColumn => Math.Min(StartColumn, EndColumn);
        
        public int MaxRow => Math.Max(StartRow, EndRow);
        public int MaxColumn => Math.Max(StartColumn, EndColumn);

        public int RowSpan => Math.Abs(EndRow - StartRow) + 1;
        public int ColumnSpan => Math.Abs(EndColumn - StartColumn) + 1;

        public CellRange(int row, int column)
        {
            StartRow = row;
            EndRow = row;
            StartColumn = column;
            EndColumn = column;
        }

        public CellRange(int startRow, int startColumn, int endRow, int endColumn)
        {
            StartRow = startRow;
            EndRow = endRow;
            StartColumn = startColumn;
            EndColumn = endColumn;
        }

        public override string ToString() => $"({StartColumn}, {StartRow}) -> ({EndColumn}, {EndRow})";
    }

    private void ClearSelection()
    {
        if (Selection is null) return;

        Children.Remove(Selection);
        Selection = null;

        UpdateSecondarySelection();
    }

    private void StartSelection(int row, int column)
    {
        if (Selection is not null) ClearSelection();

        Selection = new CellSelection(row, column, row, column, CellSelection.SelectionTypes.Main);
        Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
        Children.Add(Selection);

        UpdateSecondarySelection();
    }
    private void StartRowSelection(int row)
    {
        if (Selection is not null) ClearSelection();

        Selection = new CellSelection(row, 0, row, ColumnDefinitions.Count - 1, CellSelection.SelectionTypes.Main);
        Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
        Children.Add(Selection);

        UpdateSecondarySelection();
    }
    private void StartColumnSelection(int column)
    {
        if (Selection is not null) ClearSelection();

        Selection = new CellSelection(0, column, RowDefinitions.Count - 1, column, CellSelection.SelectionTypes.Main);
        Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
        Children.Add(Selection);

        UpdateSecondarySelection();
    }

    private Tuple<int, int> GetRowColIndex(Point point)
    {
        int rowIdx = -1;
        int colIdx = -1;
        for(var c = 0; c < ColumnDefinitions.Count; ++c)
        {
            var column = ColumnDefinitions[c];
            if(point.X >= column.Offset && point.X < column.Offset + column.ActualWidth)
            {
                colIdx = c;
                break;
            }
        }
        for(var r = 0; r < RowDefinitions.Count; ++r)
        {
            var row = RowDefinitions[r];
            if(point.Y >= row.Offset && point.Y < row.Offset + row.ActualHeight)
            {
                rowIdx = r;
                break;
            }
        }
        return new Tuple<int, int>(rowIdx, colIdx);
    }

    private void UpdateSecondarySelection()
    {
        List<DFLayoutControl> items;
        if (Selection is null || Selection.IsRowSelection || Selection.IsColumnSelection)
        {
            items = new List<DFLayoutControl>();
        }
        else
        {
            items = GetSelectedItems().ToList();
        }

        var removes = new List<DFLayoutControl>();
        foreach(var (control, selection) in SelectedItemsSelections)
        {
            if (!items.Contains(control))
            {
                removes.Add(control);
                Children.Remove(selection);
            }
        }
        foreach(var remove in removes)
        {
            SelectedItemsSelections.Remove(remove);
        }

        foreach(var item in items)
        {
            if (!SelectedItemsSelections.ContainsKey(item))
            {
                var selection = new CellSelection(
                    item.Row, item.Column,
                    item.Row + item.RowSpan - 1, item.Column + item.ColumnSpan - 1,
                    CellSelection.SelectionTypes.Secondary);
                SelectedItemsSelections.Add(item, selection);
                Children.Add(selection);
            }
        }
    }

    private void ContinueSelection(int row, int column)
    {
        if (Selection is null) return;

        row = Math.Max(row, 1);
        column = Math.Max(column, 1);

        Selection.Selecting = true;

        if (Selection.IsRowSelection)
        {
            Selection.EndRow = row;
        }
        else if (Selection.IsColumnSelection)
        {
            Selection.EndColumn = column;
        }
        else
        {
            Selection.SetEnd(row, column);
        }

        UpdateSecondarySelection();
    }

    private void Grid_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (!IsDesigning) return;
        if(Resizer is not null)
        {
            if (Resizer.StartDragging(e.GetPosition(Resizer)))
            {
                Cursor = Resizer.DragDirection switch
                {
                    CellSelection.Direction.All => Cursors.SizeAll,
                    CellSelection.Direction.Left or CellSelection.Direction.Right => Cursors.SizeWE,
                    _ => Cursors.SizeNS
                };
                if(Resizer.DragDirection == CellSelection.Direction.All)
                {
                    StartDragPosition = GetRowColIndex(e.GetPosition(this));
                }
            }
            return;
        }

        var (row, column) = GetRowColIndex(e.GetPosition(this));

        if(Selection is not null && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
        {
            ContinueSelection(row, column);
        }
        else if(Selection is not null && Selection.Selecting)
        {
            Selection.Selecting = false;
        }
        else
        {
            if (column == 0)
            {
                if (row == 0) return;
                StartRowSelection(row);
            }
            else if (row == 0)
            {
                if (column == 0) return;
                StartColumnSelection(column);
            }
            else
            {
                StartSelection(row, column);
            }
        }
    }

    private void Grid_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (!IsDesigning) return;

        var (row, column) = GetRowColIndex(e.GetPosition(this));
        if (Resizer is not null)
        {
            ResizeMouseMove(sender, e);
            return;
        }

        if (Selection is null || !Selection.Selecting) return;
        
        ContinueSelection(row, column);
    }

    private void Grid_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if(Resizer is not null)
        {
            Resizer.DragDirection = CellSelection.Direction.None;
            Cursor = Cursors.Arrow;
        }
        else if (Selection is not null)
        {
            Selection.Selecting = false;
        }
    }

    private IEnumerable<Tuple<DFLayoutControl, FrameworkElement>> GetSelectedMaps(CellRange? range = null)
    {
        range ??= Selection?.ToRange();
        if (range is null) yield break;

        var minRow = Math.Min(range.StartRow, range.EndRow);
        var maxRow = Math.Max(range.StartRow, range.EndRow);
        var minCol = Math.Min(range.StartColumn, range.EndColumn);
        var maxCol = Math.Max(range.StartColumn, range.EndColumn);

        foreach(var (control, element) in elementmap)
        {
            if(control.Row <= maxRow && control.Row + control.RowSpan - 1 >= minRow
                && control.Column <= maxCol && control.Column + control.ColumnSpan - 1 >= minCol)
            {
                yield return new(control, element);
            }
        }
    }

    private IEnumerable<DFLayoutControl> GetSelectedItems(CellRange? range = null) => GetSelectedMaps(range).Select(x => x.Item1);

    private void PopulateSelectionMenu(ContextMenu menu)
    {
        if (Selection is null) return;

        if (Selection.IsRowSelection)
        {
            var nRows = Math.Abs(Selection.EndRow - Selection.StartRow) + 1;
            if (nRows == 1)
            {
                PopulateRowMenu(menu, Selection.StartRow - 1);
            }
            else
            {
                menu.AddItem(nRows == 1 ? "Delete Row" : "Delete Rows", null, new Range(Selection.StartRow - 1, Selection.EndRow - 1), DeleteRows);
            }
        }
        else if (Selection.IsColumnSelection)
        {
            var nColumns = Math.Abs(Selection.EndColumn - Selection.StartColumn) + 1;
            if (nColumns == 1)
            {
                PopulateColumnMenu(menu, Selection.StartColumn - 1);
            }
            else
            {
                menu.AddItem(nColumns == 1 ? "Delete Column" : "Delete Columns", null, new Range(Selection.StartColumn - 1, Selection.EndColumn - 1), DeleteColumns);
            }
        }
        else
        {
            var selectedItems = GetSelectedItems().ToList();
            if (selectedItems.Count == 0)
            {
                PopulateEmptyCellMenu(menu, Selection.ToRange());
            }
            if (selectedItems.Count == 1)
            {
                var item = selectedItems.First();

                PopulateElementContextMenu(menu, item);
            }
            else if (selectedItems.Count > 1)
            {
                menu.AddItem("Delete Items", null, selectedItems, DeleteElements);
            }
        }
    }

    private void Selection_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (!IsDesigning || Selection is null) return;

        var menu = new ContextMenu();

        PopulateSelectionMenu(menu);

        if(menu.Items.Count == 0)
        {
            menu.AddItem("No actions available", null, null, false);
        }
        menu.IsOpen = true;
    }

    #endregion

    #region Resizing

    private CellSelection? Resizer;
    private Tuple<int, int> StartDragPosition;

    private CellSelection? TopResizeBackground;
    private CellSelection? LeftResizeBackground;
    private CellSelection? RightResizeBackground;
    private CellSelection? BottomResizeBackground;

    private DFLayoutControl? ResizingControl;

    private CellSelection GetResizeBackground(ref CellSelection? background)
    {
        if(background is null)
        {
            background = new CellSelection(0, 0, 0, 0, CellSelection.SelectionTypes.ResizeBackground);
            background.PreviewMouseDown += ResizerBackground_PreviewMouseDown;
            Children.Add(background);
        }
        return background;
    }
    private void ClearResizeBackground(ref CellSelection? background)
    {
        if(background is not null)
        {
            Children.Remove(background);
            background = null;
        }
    }

    private void ResizerBackground_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        FinishResize();
    }

    private void SetResizerBackgroundSize(CellSelection background, int startRow, int startColumn, int endRow, int endColumn)
    {
        background.SetSize(startRow, startColumn, endRow, endColumn);
        background.Visibility = endColumn >= startColumn && endRow >= startRow ? Visibility.Visible : Visibility.Collapsed;
    }

    private void UpdateResizer(CellRange newSize)
    {
        if (Resizer is null) return;

        Resizer.StartRow = newSize.StartRow;
        Resizer.StartColumn = newSize.StartColumn;
        Resizer.EndRow = newSize.EndRow;
        Resizer.EndColumn = newSize.EndColumn;

        SetResizerBackgroundSize(GetResizeBackground(ref LeftResizeBackground), 0, 0, RowDefinitions.Count - 1, newSize.MinColumn - 1);
        SetResizerBackgroundSize(GetResizeBackground(ref RightResizeBackground), 0, newSize.MaxColumn + 1, RowDefinitions.Count - 1, ColumnDefinitions.Count - 1);
        SetResizerBackgroundSize(GetResizeBackground(ref TopResizeBackground), 0, newSize.MinColumn, newSize.MinRow - 1, newSize.MaxColumn);
        SetResizerBackgroundSize(GetResizeBackground(ref BottomResizeBackground), newSize.MaxRow + 1, newSize.MinColumn, RowDefinitions.Count - 1, newSize.MaxColumn);
    }

    private void ResizeMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (Resizer is null) return;
        if (!Resizer.IsDragging) return;

        var (row, column) = GetRowColIndex(e.GetPosition(this));

        var newSize = Resizer.ToRange();

        switch (Resizer.DragDirection)
        {
            case CellSelection.Direction.Right:
                var startColumn = newSize.MinColumn;
                for (int c = column; c >= startColumn; --c)
                {
                    newSize.StartColumn = startColumn;
                    newSize.EndColumn = Math.Max(c, startColumn);
                    if (ResizeAllowed(newSize))
                    {
                        break;
                    }
                }
                break;
            case CellSelection.Direction.Left:
                var endColumn = newSize.MaxColumn;
                for (int c = column; c <= endColumn; ++c)
                {
                    newSize.StartColumn = Math.Min(c, endColumn);
                    newSize.EndColumn = endColumn;
                    if (ResizeAllowed(newSize))
                    {
                        break;
                    }
                }
                break;
            case CellSelection.Direction.Bottom:
                var startRow = newSize.MinRow;
                for (int r = row; r >= startRow; --r)
                {
                    newSize.StartRow = startRow;
                    newSize.EndRow = Math.Max(r, startRow);
                    if (ResizeAllowed(newSize))
                    {
                        break;
                    }
                }
                break;
            case CellSelection.Direction.Top:
                var endRow = newSize.MaxRow;
                for (int r = row; r <= endRow; ++r)
                {
                    newSize.StartRow = Math.Min(r, endRow);
                    newSize.EndRow = endRow;
                    if (ResizeAllowed(newSize))
                    {
                        break;
                    }
                }
                break;
            case CellSelection.Direction.None:
                return;
        }
        UpdateResizer(newSize);
    }

    private bool ResizeAllowed(CellRange range)
    {
        var items = GetSelectedItems(range).ToList();
        if (items.Count > 1) return false;
        return items.Count == 0 ||
            (items.Count == 1 && items.First() == ResizingControl);
    }

    private void ClearResize()
    {
        if (Resizer is null) return;

        Children.Remove(Resizer);
        Resizer = null;
        ResizingControl = null;

        ClearResizeBackground(ref LeftResizeBackground);
        ClearResizeBackground(ref RightResizeBackground);
        ClearResizeBackground(ref TopResizeBackground);
        ClearResizeBackground(ref BottomResizeBackground);
    }

    private void FinishResize()
    {
        if (Resizer is null) return;

        var range = Resizer.ToRange();

        if(ResizingControl is not null)
        {
            ResizingControl.Row = range.MinRow;
            ResizingControl.Column = range.MinColumn;
            ResizingControl.RowSpan = range.RowSpan;
            ResizingControl.ColumnSpan = range.ColumnSpan;
        }

        ClearResize();
        Render();
    }

    private void ResizeItem(DFLayoutControl control)
    {
        ClearSelection();
        ClearResize();

        Resizer = new CellSelection(
            control.Row, control.Column,
            control.Row + control.RowSpan - 1, control.Column + control.ColumnSpan - 1,
            CellSelection.SelectionTypes.Resizable);
        ResizingControl = control;
        Children.Add(Resizer);

        UpdateResizer(Resizer.ToRange());
    }

    public void HandleKeyDown(KeyEventArgs e)
    {
        if (Resizer is null) return;
        if(e.Key == Key.Enter)
        {
            FinishResize();
        }
        else if(e.Key == Key.Escape)
        {
            ClearResize();
        }
    }

    #endregion

    #region Rows

    private void ShiftDown(int row)
    {
        foreach (var element in form.Elements)
            if (element.Row > row)
                element.Row++;
            else if (element.Row + element.RowSpan - 1 > row)
                element.RowSpan++;
    }

    private void AddRowBeforeClick(int row)
    {
        var length = new GridLength(1.0F, GridUnitType.Auto);
        var result = GridLengthToString(length);
        if (form.RowHeights.Count == 0)
            form.RowHeights.Add(result);
        else
            form.RowHeights.Insert(row, result);
        ShiftDown(row);
        Render();
    }

    private void AddRowAfterClick(int row)
    {
        var length = new GridLength(1.0F, GridUnitType.Auto);
        var result = GridLengthToString(length);
        if (row == form.RowHeights.Count - 1)
            form.RowHeights.Add(result);
        else
            form.RowHeights.Insert(row + 1, result);
        ShiftDown(row + 1);
        Render();
    }

    private void SplitRow(int row)
    {
        foreach (var element in form.Elements)
            if (element.Row > row)
                element.Row++;
            else if (element.Row == row)
                element.RowSpan++;
            else if (element.Row + element.RowSpan - 1 >= row)
                element.RowSpan++;
    }

    private void SplitRowClick(int row)
    {
        var height = StringToGridLength(form.RowHeights[row]);
        var newHeight = height.GridUnitType == GridUnitType.Auto
            ? height
            : new GridLength(height.Value / 2, height.GridUnitType);
        var result = GridLengthToString(newHeight);
        form.RowHeights[row] = result;
        
        if (row == form.RowHeights.Count - 1)
            form.RowHeights.Add(result);
        else
            form.RowHeights.Insert(row + 1, result);
        SplitRow(row + 1);
        Render();
    }

    private void RowPropertiesClick(int row)
    {
        var length = StringToGridLength(form.RowHeights[row]);

        var editor = new DynamicFormDesignLength(length);
        if (editor.ShowDialog() == true)
        {
            form.RowHeights[row] = GridLengthToString(editor.GridLength);
            Render();
        }
    }

    private void ShiftUp(int row)
    {
        var deletes = new List<DFLayoutControl>();
        foreach (var element in form.Elements)
            if (element.Row > row)
                element.Row--;
            else if (element.Row == row && element.RowSpan <= 1)
                deletes.Add(element);
            else if (element.Row + element.RowSpan - 1 >= row)
                element.RowSpan--;
        foreach (var delete in deletes)
            form.Elements.Remove(delete);
    }

    private void DeleteRows(Range rows)
    {
        for(var row = rows.Max; row >= rows.Min; --row)
        {
            form.RowHeights.RemoveAt(row);
            ShiftUp(row + 1);
        }
        if(form.RowHeights.Count == 0)
        {
            form.RowHeights.Add("Auto");
        }
        Render();
    }

    private void PopulateRowMenu(ContextMenu menu, int row)
    {
        menu.AddItem("Add Row Before", null, row, AddRowBeforeClick);
        menu.AddItem("Add Row After", null, row, AddRowAfterClick);
        menu.AddSeparator();
        menu.AddItem("Split Row", null, row, SplitRowClick);

        var propertiesSeparator = menu.AddSeparator();
        var propertiesMenu = menu.AddItem("Row Properties", null, row, RowPropertiesClick);

        menu.AddSeparator();
        menu.AddItem("Delete Row", null, new Range(row, row), DeleteRows);
        menu.Opened += (o, e) =>
        {
            propertiesSeparator.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
            propertiesMenu.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
        };
    }

    private ContextMenu CreateRowMenu(Button button, int row)
    {
        var result = new ContextMenu();
        PopulateRowMenu(result, row);
        button.SetValue(ContextMenuProperty, result);
        return result;
    }

    #endregion

    #region Columns

    private void ShiftRight(int column)
    {
        foreach (var element in form.Elements)
            if (element.Column > column)
                element.Column++;
            else if (element.Column + element.ColumnSpan - 1 > column)
                element.ColumnSpan++;
    }

    private void AddColumnBeforeClick(int column)
    {
        var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
        var result = GridLengthToString(length);
        if (form.ColumnWidths.Count == 0)
            form.ColumnWidths.Add(result);
        else
            form.ColumnWidths.Insert(column, result);
        ShiftRight(column);
        Render();
    }

    private void AddColumnAfterClick(int column)
    {
        var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);

        var result = GridLengthToString(length);
        if (column == form.ColumnWidths.Count - 1)
            form.ColumnWidths.Add(result);
        else
            form.ColumnWidths.Insert(column + 1, result);
        ShiftRight(column + 1);
        Render();
    }

    private void SplitColumn(int column)
    {
        foreach (var element in form.Elements)
            if (element.Column > column)
                element.Column++;
            else if (element.Column == column)
                element.ColumnSpan++;
            else if (element.Column + element.ColumnSpan - 1 >= column)
                element.ColumnSpan++;
    }

    private void SplitColumnClick(int column)
    {
        var length = StringToGridLength(form.ColumnWidths[column]);
        var newLength = length.GridUnitType == GridUnitType.Auto
            ? length
            : new GridLength(length.Value / 2, length.GridUnitType);
        var result = GridLengthToString(newLength);
        form.ColumnWidths[column] = result;

        if (column == form.ColumnWidths.Count - 1)
            form.ColumnWidths.Add(result);
        else
            form.ColumnWidths.Insert(column + 1, result);
        SplitColumn(column + 1);
        Render();
    }

    private void ColumnPropertiesClick(int column)
    {
        var length = StringToGridLength(form.ColumnWidths[column]);

        var editor = new DynamicFormDesignLength(length);
        if (editor.ShowDialog() == true)
        {
            form.ColumnWidths[column] = GridLengthToString(editor.GridLength);
            Render();
        }
    }

    private void ShiftLeft(int column)
    {
        var deletes = new List<DFLayoutControl>();
        foreach (var element in form.Elements)
            if (element.Column > column)
                element.Column--;
            else if (element.Column == column && element.ColumnSpan <= 1)
                deletes.Add(element);
            else if (element.Column + element.ColumnSpan - 1 >= column)
                element.ColumnSpan--;
        foreach (var delete in deletes)
            form.Elements.Remove(delete);
    }

    private void DeleteColumns(Range columns)
    {
        for(var column = columns.Max; column >= columns.Min; --column)
        {
            form.ColumnWidths.RemoveAt(column);
            ShiftLeft(column + 1);
        }
        if(form.ColumnWidths.Count == 0)
        {
            form.ColumnWidths.Add("*");
        }
        Render();
    }

    private void PopulateColumnMenu(ContextMenu menu, int column)
    {
        menu.AddItem("Add Column Before", null, column, AddColumnBeforeClick);
        menu.AddItem("Add Column After", null, column, AddColumnAfterClick);
        menu.AddSeparator();
        menu.AddItem("Split Column", null, column, SplitColumnClick);
        var propertiesSeparator = menu.AddSeparator();
        var propertiesMenu = menu.AddItem("Column Properties", null, column, ColumnPropertiesClick);
        menu.AddSeparator();
        menu.AddItem("Delete Column", null, new Range(column, column), DeleteColumns);
        menu.Opened += (o, e) =>
        {
            propertiesSeparator.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
            propertiesMenu.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
        };
    }

    private ContextMenu CreateColumnMenu(Button button, int column)
    {
        var result = new ContextMenu();
        PopulateColumnMenu(result, column);
        button.SetValue(ContextMenuProperty, result);
        return result;
    }

    #endregion

    #region Add Element

    private void AddNewElement<TElement>(DynamicFormElement elementDef, CellRange range)
        where TElement : DFLayoutElement, new()
    {
        TElement? element;
        if (elementDef.CreateElement is not null)
        {
            element = elementDef.CreateElement(elementDef.Tag) as TElement;
        }
        else
        {
            element = new();
        }
        if(element is null)
        {
            return;
        }
        SetControlRange(element, range);

        var result = new FormControlGrid<TElement>().EditItems(new[] { element });
        if (result)
        {
            form.Elements.Add(element);
            Render();
        }
    }

    private void AddElementClick(Tuple<DynamicFormElement, CellRange> tuple)
    {
        var method = typeof(DynamicFormDesignGrid)
            .GetMethod(nameof(AddNewElement), BindingFlags.NonPublic | BindingFlags.Instance)!
            .MakeGenericMethod(tuple.Item1.ElementType);
        method.Invoke(this, new object[] { tuple.Item1, tuple.Item2 });
    }

    private void ElementActionClick(Tuple<DynamicFormElementAction, CellRange> tuple)
    {
        var element = tuple.Item1.OnClick(tuple.Item1.Tag);
        if(element is not null)
        {
            SetControlRange(element, tuple.Item2);
            form.Elements.Add(element);
            Render();
        }
    }

    private void SetControlRange(DFLayoutControl control, CellRange range)
    {
        var minRow = Math.Min(range.StartRow, range.EndRow);
        var maxRow = Math.Max(range.StartRow, range.EndRow);
        var minColumn = Math.Min(range.StartColumn, range.EndColumn);
        var maxColumn = Math.Max(range.StartColumn, range.EndColumn);

        control.Row = minRow;
        control.RowSpan = (maxRow - minRow) + 1;
        control.Column = minColumn;
        control.ColumnSpan = (maxColumn - minColumn) + 1;
    }

    private void CreateLabelClick(CellRange range)
    {
        var label = new DFLayoutLabel();
        SetControlRange(label, range);
        var result = new FormControlGrid<DFLayoutLabel>().EditItems(new[] { label });
        if (result)
        {
            form.Elements.Add(label);
            Render();
        }
    }

    private void CreateHeaderClick(CellRange range)
    {
        var header = new DFLayoutHeader();
        SetControlRange(header, range);
        var result = new FormControlGrid<DFLayoutHeader>().EditItems(new[] { header });
        if (result)
        {
            form.Elements.Add(header);
            Render();
        }
    }

    private void CreateImageClick(CellRange range)
    {
        var image = new DFLayoutImage();
        SetControlRange(image, range);
        var result = new FormControlGrid<DFLayoutImage>().EditItems(new[] { image });
        if (result)
        {
            form.Elements.Add(image);
            Render();
        }
    }

    private void AddVariable(Tuple<DigitalFormVariable, CellRange> tuple)
    {
        if(Activator.CreateInstance(tuple.Item1.FieldType()) is not DFLayoutField field)
        {
            MessageBox.Show(string.Format("{0}: Unknown Type {1}", tuple.Item1.Code, tuple.Item1.VariableType.ToString()));
            return;
        }

        field.Name = tuple.Item1.Code;
        SetControlRange(field, tuple.Item2);
        form.Elements.Add(field);
        form.LoadVariable(tuple.Item1, field);
        Render();
    }

    private void PopulateEmptyCellMenu(ContextMenu menu, CellRange cellRange)
    {
        menu.Items.Clear();
        menu.AddItem("Add Label", null, cellRange, CreateLabelClick);
        menu.AddItem("Add Header", null, cellRange, CreateHeaderClick);
        menu.AddItem("Add Image", null, cellRange, CreateImageClick);

        var fields = menu.AddItem("Add Field", null, null);

        if (OnCreateVariable is not null)
        {
            var variables = fields.AddItem("Create new variable", null, null);

            foreach (var fieldType in DFUtils.GetFieldTypes())
            {
                var caption = fieldType.GetCaption();
                if (string.IsNullOrWhiteSpace(caption))
                {
                    caption = CoreUtils.Neatify(fieldType.Name);
                }
                variables.AddItem(caption, null, new Tuple<Type, CellRange>(fieldType, cellRange), (tuple) =>
                {
                    var variable = OnCreateVariable?.Invoke(tuple.Item1);
                    if (variable is not null)
                    {
                        _variables.Add(variable);
                        AddVariable(new(variable, tuple.Item2));
                    }
                });
            }
        }

        var filtered = _variables.Where(x => !x.Hidden && !form.Elements.Any(v => string.Equals((v as DFLayoutField)?.Name, x.Code)));
        fields.AddSeparatorIfNeeded();
        foreach (var variable in filtered)
            fields.AddItem(variable.Code, null, new Tuple<DigitalFormVariable, CellRange>(variable, cellRange), AddVariable);
        fields.RemoveUnnecessarySeparators();
        if(fields.Items.Count == 0)
        {
            menu.Items.Remove(fields);
        }

        var elements = menu.AddItem("Add Object", null, cellRange, null);

        var available = _elements.Where(x => x.Visible && (x.AllowDuplicate || !form.Elements.Any(v => (v as DFLayoutElement)?.GetType() == x.ElementType)))
            .ToArray();

        var cats = available.Select(x => x.Category).Concat(_elementActions.Select(x => x.Category)).Distinct().OrderBy(x => x);
        foreach (var cat in cats)
        {
            var parentMenu = elements;
            if (!string.IsNullOrWhiteSpace(cat))
            {
                parentMenu = elements.AddItem(cat, null, null);
            }

            foreach(var action in _elementActions.Where(x => x.Category == cat))
            {
                parentMenu.AddItem(action.Caption, action.Image, new Tuple<DynamicFormElementAction, CellRange>(action, cellRange), ElementActionClick);
            }

            parentMenu.AddSeparatorIfNeeded();

            foreach (var element in available.Where(x => string.Equals(x.Category, cat)))
                parentMenu.AddItem(element.Caption, null, new Tuple<DynamicFormElement, CellRange>(element, cellRange), AddElementClick);
            parentMenu.RemoveUnnecessarySeparators();
        }

        if (elements.Items.Count == 0)
            menu.Items.Remove(elements);
    }

    private ContextMenu CreateEmptyCellMenu(Border border, int row, int column)
    {
        var result = new ContextMenu();
        result.Opened += (o, e) =>
        {
            PopulateEmptyCellMenu(result, new CellRange(row, column));
        };

        border.SetValue(ContextMenuProperty, result);
        return result;
    }

    #endregion

    #region Element Context Menu

    private void DeleteElements(IEnumerable<DFLayoutControl> controls)
    {
        foreach(var control in controls)
        {
            if (form.Elements.Contains(control))
            {
                form.Elements.Remove(control);
            }
        }
        Render();
    }

    private void DeleteElementClick(DFLayoutControl control)
    {
        if (form.Elements.Contains(control))
        {
            form.Elements.Remove(control);
            Render();
        }
    }

    private void ElementPropertiesClick(DFLayoutControl control)
    {
        if(!elementgrids.TryGetValue(control.GetType(), out var grid))
        {
            var type = typeof(FormControlGrid<>).MakeGenericType(control.GetType());
            grid = (Activator.CreateInstance(type) as IDynamicGrid)!;
            elementgrids[control.GetType()] = grid;
        }

        control.CommitChanges();
        if (grid.EditItems(new[] { control }))
        {
            Render();
        }
    }

    private void EditVariableClick(DFLayoutField field)
    {
        var variable = _variables.FirstOrDefault(x => x.Code == field.Name);
        if (variable is null) return;

        if(OnEditVariable?.Invoke(variable) == true)
        {
            field.LoadFromString(variable.Parameters);
        }
    }

    private void ConvertToHeaderClick(DFLayoutLabel label)
    {
        var header = new DFLayoutHeader
        {
            Row = label.Row,
            RowSpan = label.RowSpan,
            Column = label.Column,
            ColumnSpan = label.ColumnSpan,
            Collapsed = false,
            Header = label.Caption
        };
        header.Style.Synchronise(label.Style);
        header.Style.IsBold = true;
        form.Elements.Remove(label);
        form.Elements.Add(header);
        Render();
    }

    private void ConvertToLabelClick(DFLayoutHeader header)
    {
        var label = new DFLayoutLabel
        {
            Row = header.Row,
            RowSpan = header.RowSpan,
            Column = header.Column,
            ColumnSpan = header.ColumnSpan,
            Caption = header.Header
        };
        label.Style.Synchronise(header);
        label.Style.IsBold = false;

        form.Elements.Remove(header);
        form.Elements.Add(label);
        Render();
    }

    private void PopulateElementContextMenu(ContextMenu menu, DFLayoutControl control)
    {
        var selectedItems = GetSelectedItems().ToList();
        if (selectedItems.Count > 1 && selectedItems.Contains(control))
        {
            PopulateSelectionMenu(menu);
            if(menu.Items.Count > 0) return;
        }

        menu.AddItem("Edit Properties", null, control, ElementPropertiesClick);
        if (OnEditVariable is not null && control is DFLayoutField field)
        {
            menu.AddItem("Edit Variable", null, field, EditVariableClick);
        }
        else if (control is DFLayoutLabel label)
        {
            menu.AddItem("Convert to Header", null, label, ConvertToHeaderClick);
        }
        else if (control is DFLayoutHeader header)
        {
            menu.AddItem("Convert to Label", null, header, ConvertToLabelClick);
        }
        else if(control is DFLayoutElement element)
        {
            CustomiseElementContextMenu?.Invoke(menu, element);
        }
        menu.AddSeparatorIfNeeded();
        menu.AddItem("Resize Item", null, control, ResizeItem);
        menu.AddItem("Delete Item", null, control, DeleteElementClick);
    }

    private ContextMenu CreateElementContextMenu(FrameworkElement element, DFLayoutControl control)
    {
        var result = new ContextMenu();
        result.Opened += (s, e) =>
        {
            result.Items.Clear();
            PopulateElementContextMenu(result, control);
        };
        element.SetValue(ContextMenuProperty, result);
        return result;
    }

    #endregion

    #endregion

    #region Render

    private static void SetDimensions(FrameworkElement element, int row, int column, int rowspan, int colspan, int offset)
    {
        if (column <= 0) return;
        if (row <= 0) return;

        element.MinHeight = 50.0F;
        element.MinWidth = 50.0F;
        element.SetGridPosition(row - offset, column - offset, rowspan, colspan);
    }

    private Border CreateBorder(int row, int column, int rowspan, int colspan, int offset, bool horzstar, bool vertstar)
    {
        var border = new Border();
        if (ShowBorders)
        {
            border.BorderThickness = new Thickness(
                0.0F,//!IsDesigning && column == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
                0.0F,//!IsDesigning && row == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
                column - offset == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
                row - offset == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
            );

            border.BorderBrush = BorderBrush;
        }

        border.Background = BackgroundBrush;

        SetDimensions(border, row, column, rowspan, colspan, offset);

        return border;
    }

    private static BitmapImage HeaderClosed =Wpf.Resources.rightarrow.AsBitmapImage(32, 32);
    private static BitmapImage HeaderOpen =Wpf.Resources.downarrow.AsBitmapImage(32, 32);

    private FrameworkElement CreateHeader(DFLayoutHeader header)
    {
        var formHeader = new FormHeader
        {
            Collapsed = header.Collapsed,
            HeaderText = header.Header
        };
        formHeader.CollapsedChanged += (o, c) =>
        {
            CollapseRows(formHeader, c);
        };
        if (IsDesigning)
        {
            formHeader.IsEnabled = false;
        }
        return formHeader;
    }

    // DFLayoutField -> IDynamicFormFieldControl
    private static Dictionary<Type, Type>? _fieldControls;
    private DynamicFormControl? CreateFieldControl(DFLayoutField field)
    {
        if (_fieldControls == null)
        {
            _fieldControls = new();
            foreach (var controlType in CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.HasInterface<IDynamicFormFieldControl>()))
            {
                var superDefinition = controlType.GetSuperclassDefinition(typeof(DynamicFormFieldControl<,,,>));
                if (superDefinition != null)
                {
                    _fieldControls[superDefinition.GenericTypeArguments[0]] = controlType;
                }
            }
        }

        var fieldControlType = _fieldControls.GetValueOrDefault(field.GetType());
        if (fieldControlType is not null)
        {
            var element = (Activator.CreateInstance(fieldControlType) as DynamicFormControl)!;

            if(element is IDynamicFormFieldControl fieldControl)
            {
                fieldControl.FieldChangedEvent += () =>
                {
                    ChangeField(field.Name);
                };
            }

            return element;
        }
        return null;
    }

    private DynamicFormControl? CreateFieldPlaceholder(DFLayoutField field)
    {
        var controlType = typeof(DFFieldPlaceholderControl<>).MakeGenericType(field.GetType());
        return Activator.CreateInstance(controlType) as DynamicFormControl;
    }

    private DynamicFormControl? CreateControl(DFLayoutControl item)
    {
        if (item is DFLayoutField field)
        {
            if (IsDesigning)
            {
                return CreateFieldPlaceholder(field);
            }

            return CreateFieldControl(field);
        }
        else if (item is DFLayoutElement)
        {
            return IsDesigning
                ? new DFElementPlaceholderControl()
                : new DFElementControl();
        }
        else if (item is DFLayoutLabel)
        {
            return new DFLabelControl();
        }
        else if (item is DFLayoutHeader)
        {
            return new DFHeaderControl();
        }
        else if (item is DFLayoutImage)
        {
            return new DFImageControl();
        }

        return null;
    }

    private FrameworkElement? CreateElement(DFLayoutControl item)
    {
        var control = CreateControl(item);
        if(control != null)
        {
            control.FormDesignGrid = this;
            control.SetControl(item);
        }
        return control;
    }

    private Brush GetItemBackgroundBrush(DFLayoutControl item, Color? colour = null)
    {
        if(colour != null)
        {
            var colourValue = colour.Value;
            return new SolidColorBrush(new System.Windows.Media.Color { R = colourValue.R, G = colourValue.G, B = colourValue.B, A = colourValue.A });
        }

        if (item is DFLayoutField field)
            return field.GetPropertyValue<bool>("Required") ? RequiredFieldBrush : FieldBrush;
        else
            return IsDesigning ? FieldBrush : BackgroundBrush;
    }

    private void RenderElement(DFLayoutControl item, int offset, bool horzstar, bool vertstar)
    {
        var border = CreateBorder(item.Row, item.Column, item.RowSpan, item.ColumnSpan, offset, horzstar, vertstar);

        border.Background = GetItemBackgroundBrush(item);

        if (!ShowBorders)
            border.Padding = new Thickness(
                item.Column == 1 ? 4 : 2,
                item.Row == 1 ? 4 : 2,
                item.Column + item.ColumnSpan - 1 == ColumnDefinitions.Count ? 4 : 2,
                item.Row + item.RowSpan - 1 == RowDefinitions.Count ? 4 : 2
            );
        else
            border.Padding = new Thickness(5);

        var element = CreateElement(item);
        border.Child = element;
        Children.Add(border);
        if (IsDesigning)
        {
            CreateElementContextMenu(border, item);
        }
        borderMap[item] = border;

        if (element != null)
        {
            if(item is DFLayoutField)
            {
                element.IsEnabled = element.IsEnabled && !IsReadOnly;
            }
            elementmap[item] = element;

            element.HorizontalAlignment = GetHorizontalAlignment(item.HorizontalAlignment);
            element.VerticalAlignment = GetVerticalAlignment(item.VerticalAlignment);
            if (IsDesigning)
            {
                CreateElementContextMenu(element, item);
            }
        }

    }

    private void AfterRender()
    {
        if (!IsDesigning)
        {
            foreach (var header in elementmap.Where(x => x.Value is DFHeaderControl head).Select(x => x.Value).Cast<DFHeaderControl>())
            {
                if (header.Header.Collapsed)
                {
                    CollapseRows(header.Header, true);
                }
            }
        }

        OnAfterRender?.Invoke(this);
    }

    private void Render()
    {
        ClearSelection();
        ClearResize();

        foreach (var item in elementmap.Keys)
        {
            var e = elementmap[item];
            if (VisualTreeHelper.GetParent(e) is Border parent)
                parent.Child = null;
        }

        elementmap.Clear();

        Children.Clear();

        ColumnDefinitions.Clear();

        RowDefinitions.Clear();

        if (form == null)
            return;

        foreach (var column in form.ColumnWidths)
            ColumnDefinitions.Add(new ColumnDefinition { Width = StringToGridLength(column) });

        foreach (var row in form.RowHeights)
            RowDefinitions.Add(new RowDefinition { Height = StringToGridLength(row), Tag = new RowData(row) });

        var horzstar = ColumnDefinitions.Any(x => x.Width.IsStar);
        var vertstar = RowDefinitions.Any(x => x.Height.IsStar);

        var offset = 1;
        if (IsDesigning)
        {
            ColumnDefinitions.Insert(0, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
            RowDefinitions.Insert(0, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });

            var topleft = new Button();
            topleft.SetValue(RowProperty, 0);
            topleft.SetValue(ColumnProperty, 0);
            topleft.Content =
                ""; // new Image() { Source = _designing ? Wpf.Resources.view.AsBitmapImage() : Wpf.Resources.design.AsBitmapImage() };
            topleft.BorderBrush = BorderBrush;
            topleft.BorderThickness = new Thickness(
                0.00F,
                0.00F,
                0.75F,
                0.75F
            );
            topleft.Background = BackgroundBrush;
            //topleft.Click += (o, e) =>
            //{
            //    Designing = !Designing;
            //};
            Children.Add(topleft);

            for (var i = 1; i < ColumnDefinitions.Count; i++)
            {
                var Button = new Button();
                Button.SetValue(RowProperty, 0);
                Button.SetValue(ColumnProperty, i);
                Button.Content = FormatGridLength(ColumnDefinitions[i].Width, ColumnDefinitions.Select(x => x.Width));
                Button.BorderBrush = BorderBrush;
                Button.BorderThickness = new Thickness(
                    0.00F, //(i == 1) ? 0.75F : 0.0F,
                    0.00F, //0.75F,
                    i == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
                    0.75F
                );
                Button.Background = BackgroundBrush;
                Button.Padding = new Thickness(10);
                Button.MinHeight = 35;
                CreateColumnMenu(Button, i - 1);
                AddClick(Button, i - 1, ColumnPropertiesClick);
                Children.Add(Button);
            }

            for (var i = 1; i < RowDefinitions.Count; i++)
            {
                var Button = new Button();
                Button.SetValue(RowProperty, i);
                Button.SetValue(ColumnProperty, 0);
                Button.Content = FormatGridLength(RowDefinitions[i].Height, RowDefinitions.Select(x => x.Height));
                Button.BorderBrush = BorderBrush;
                Button.BorderThickness = new Thickness(
                    0.00F, //0.75F,
                    0.00F, //(i == 1) ? 0.75F : 0.0F,
                    0.75F,
                    i == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
                );
                Button.Background = BackgroundBrush;
                Button.Padding = new Thickness(10);
                CreateRowMenu(Button, i - 1);
                AddClick(Button, i - 1, RowPropertiesClick);
                Children.Add(Button);
            }

            offset = 0;
        }

        var filledcells = new HashSet<PointI>();
        foreach (var item in form.GetElements(IsDesigning))
        {
            try
            {
                if(item.Row > 0 && item.Column > 0)
                {
                    RenderElement(item, offset, horzstar, vertstar);
                    for (var c = item.Column; c < item.Column + item.ColumnSpan; c++)
                        for (var r = item.Row; r < item.Row + item.RowSpan; r++)
                            filledcells.Add(new PointI(c, r));
                }
            }
            catch (Exception e)
            {
                Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
            }
        }

        for (var c = 1; c <= form.ColumnWidths.Count; c++)
            for (var r = 1; r <= form.RowHeights.Count; r++)
                if (!filledcells.Contains(new(c, r)))
                {
                    var border = CreateBorder(r, c, 1, 1, offset, horzstar, vertstar);
                    if (IsDesigning)
                    {
                        CreateEmptyCellMenu(border, r, c);
                    }
                    Children.Add(border);
                }

        AfterRender();
    }

    #endregion

    /// <summary>
    /// Renders the form; after this is called, any changes to properties triggers a refresh.
    /// </summary>
    /// <remarks>
    /// This should be called before <see cref="LoadValues(Dictionary{string, object})"/> or <see cref="SaveValues"/>
    /// </remarks>
    public void Initialize()
    {
        GridInitialized = true;
        CheckRefresh(false);
    }

    public void Refresh()
    {
        CheckRefresh(false);
    }

    private void CheckRefresh(bool keepValues = true)
    {
        if (!GridInitialized) return;

        if (_mode == FormMode.Designing)
        {
            Render();
        }
        else if(keepValues)
        {
            var values = SaveValues();
            Render();
            LoadValues(values.ToLoadStorage());
        }
        else
        {
            Render();
            Form.EvaluateExpressions();
        }
    }

    #region Fields

    private void ChangeField(string fieldName)
    {
        if (!_changing)
        {
            form.ChangeField(fieldName);
            _isChanged = true;
            OnChanged?.Invoke(this, fieldName);
        }
    }

    private IDynamicFormFieldControl? GetFieldControl(DFLayoutField field)
    {
        return elementmap.GetValueOrDefault(field) as IDynamicFormFieldControl;
    }

    private void LoadFieldValue(string fieldName, DFLoadStorageEntry entry)
    {
        var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
        if (field != null)
        {
            var fieldControl = GetFieldControl(field);
            if (fieldControl != null)
            {
                string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
                if (!property.IsNullOrWhiteSpace())
                    fieldControl.SetValue(DataModel!.GetEntityValue(property));
                else
                    fieldControl.Deserialize(entry);
            }
        }
    }

    public void SetFieldValue(string fieldName, object? value)
    {
        var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
        if (field != null)
        {
            var fieldControl = GetFieldControl(field);
            if (fieldControl != null)
            {
                string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
                if (!property.IsNullOrWhiteSpace())
                    fieldControl.SetValue(DataModel!.GetEntityValue(property));
                else
                    fieldControl.SetValue(value);
            }
        }
    }

    private void GetFieldValue(DFLayoutField field, DFSaveStorageEntry storage, out object? entityValue)
    {
        var fieldControl = GetFieldControl(field);
        if(fieldControl != null)
        {
            entityValue = fieldControl.GetEntityValue();
            fieldControl.Serialize(storage);
        }
        else
        {
            entityValue = null;
        }
    }

    public object? GetFieldValue(string fieldName)
    {
        var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
        if (field is null)
        {
            return null;
        }
        var fieldControl = GetFieldControl(field);
        return fieldControl?.GetValue();
    }

    public object? GetFieldData(string fieldName, string dataField)
    {
        var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
        if (field is null)
        {
            return null;
        }
        var fieldControl = GetFieldControl(field);
        return fieldControl?.GetData(dataField);
    }

    public void SetFieldColour(string fieldName, Color? colour)
    {
        var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
        if (field is null || !borderMap.TryGetValue(field, out var border))
        {
            return;
        }
        border.Background = GetItemBackgroundBrush(field, colour);
    }

    /// <summary>
    /// Load values into editor; Must be called after <see cref="Initialize"/>.
    /// </summary>
    /// <remarks>
    /// Resets <see cref="IsChanged"/>.
    /// </remarks>
    /// <param name="values">A storage object.</param>
    public void LoadValues(DFLoadStorage values)
    {
        _changing = true;
        InitializeEntityValues();
        foreach (var (key, value) in values.Items())
        {
            if (!key.Contains('.'))
            {
                LoadFieldValue(key, values.GetEntry(key));
            }
        }
        Form.EvaluateExpressions();
        _changing = false;
        _isChanged = false;
    }

    public void InitializeEntityValues()
    {
        _changing = true;
        foreach (var field in form.Elements.OfType<DFLayoutField>())
        {
            var property = DataModel != null ? field.GetPropertyValue<string>("Property") : null;
            if (!property.IsNullOrWhiteSpace())
            {
                var fieldControl = GetFieldControl(field);
                if(fieldControl != null)
                {
                    fieldControl.SetValue(DataModel!.GetEntityValue(property));
                }
            }
        }
        Form.EvaluateExpressions();
        _changing = false;
        _isChanged = false;
    }

    /// <summary>
    /// Takes values from editors and saves them to a dictionary; must be called after <see cref="Initialize"/>.
    /// </summary>
    /// <returns>A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</returns>
    public DFSaveStorage SaveValues()
    {
        var result = new DFSaveStorage();
        foreach (var formElement in form.Elements)
            if (formElement is DFLayoutField field)
            {
                GetFieldValue(field, result.GetEntry(field.Name), out var entityValue);

                if(DataModel != null)
                {
                    var property = field.GetPropertyValue<string>("Property");
                    if (!string.IsNullOrWhiteSpace(property))
                        DataModel.SetEntityValue(property, entityValue);
                }
            }

        return result;
    }

    public bool Validate(out List<string> messages)
    {
        messages = new List<string>();
        var valid = true;
        foreach(var formElement in form.Elements)
        {
            if(formElement is DFLayoutField field)
            {
                var fieldControl = GetFieldControl(field);
                if(fieldControl != null && !fieldControl.Validate(out var message))
                {
                    messages.Add(message);
                    valid = false;
                }
            }
        }
        return valid;
    }

    #endregion

}