using DevExpress.Utils;
using DevExpress.Utils.Controls;
using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ExtensionsDev
{
    public static class LayoutControlExtension
    {
        public static void UseDefault(this LayoutControl ctrl, bool saveLayout = false)
        {
            foreach (var item in ctrl.Root.Items)
            {
                if (item is LayoutControlItem layItem)
                {
                    layItem.AllowHtmlStringInCaption = true;
                }
            }
            ctrl.AllowTouchGestures = DevExpress.Utils.DefaultBoolean.False;
            ctrl.AllowDrop = false;
            ctrl.AllowCustomization = false;
            ctrl.OptionsFocus.AllowFocusGroups = false;
            ctrl.OptionsFocus.AllowFocusTabbedGroups = false;
            ctrl.OptionsFocus.AllowFocusControlOnLabelClick = true;
            // ctrl.Root.GroupBordersVisible = false;
            if (saveLayout)
            {
                System.Windows.Forms.Control findCtrl = ctrl;
                string GetLayoutName()
                {
                    while (findCtrl.Parent != null)
                    {
                        findCtrl = findCtrl.Parent;
                        if (findCtrl is System.Windows.Forms.UserControl) break;
                    }
                    return $"{findCtrl.Name}_{ctrl.Name}";
                }
                string name = GetLayoutName();
                EventHandler loadEvent = (sender, e) =>
                {
                    var form = ctrl.FindForm();
                    if (form != null)
                    {
                        form.VisibleChanged += (sender2, e2) =>
                        {
                            Directory.CreateDirectory("Layout");
                            if (name == null) return;
                            ctrl.SaveLayoutToXml($"Layout\\{name}.xml");
                        };
                    }
                };
                if (findCtrl is Form frm)
                {
                    frm.Load += loadEvent;
                }
                else if (findCtrl is UserControl uCtrl)
                {
                    uCtrl.Load += loadEvent;
                }

                if (name != null && File.Exists($"Layout\\{name}.xml"))
                {
                    if (Debugger.IsAttached)
                    {
                        File.Delete($"Layout\\{name}.xml");
                    }
                    else
                    {
                        ctrl.RestoreLayoutFromXml($"Layout\\{name}.xml");
                    }
                }
            }
        }

    }
}
