using AIStudio.Wpf.DiagramDesigner.Additionals.Commands;
using AIStudio.Wpf.DiagramDesigner.Additionals.Extensions.ViewModels;
using AIStudio.Wpf.DiagramDesigner.Additionals;
using AIStudio.Wpf.DiagramApp.Models;
using AIStudio.Wpf.Flowchart;
using AIStudio.Wpf.Flowchart.ViewModels;
using AIStudio.Wpf.Logical.ViewModels;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Input;
using AIStudio.Wpf.DiagramDesigner;
using AIStudio.Wpf.DiagramDesigner.Helpers;
using AIStudio.Wpf.SFC;
using AIStudio.Wpf.SFC.ViewModels;
using System.Windows.Media;
using AIStudio.Wpf.Flowchart.Models;
using AIStudio.Wpf.SFC.Models;
using System.Windows;
using System;
using AIStudio.Wpf.DiagramDesigner.Models;
using AIStudio.Wpf.DiagramDesigner.ViewModels;
using AIStudio.Wpf.DiagramDesigner.ViewModels.BaseViewModel;

namespace AIStudio.Wpf.DiagramApp.ViewModels
{
    public class ToolBoxViewModel : BindableBase
    {
        private MainWindowViewModel _mainWindowViewModel;

        public ToolBoxViewModel(MainWindowViewModel mainWindowViewModel)
        {
            _mainWindowViewModel = mainWindowViewModel;
            Init();
        }

        private ObservableCollection<ToolBoxCategory> _toolBoxCategory = new ObservableCollection<ToolBoxCategory>();
        public ObservableCollection<ToolBoxCategory> ToolBoxCategory
        {
            get
            {
                return _toolBoxCategory;
            }
            set
            {
                SetProperty(ref _toolBoxCategory, value);
            }
        }

        public ToolBoxCategory MyToolBoxCategory
        {
            get
            {
                return ToolBoxCategory?.FirstOrDefault();
            }
        }

        public ToolBoxCategory SvgToolBoxCategory
        {
            get
            {
                return ToolBoxCategory?.FirstOrDefault(p => p.Header == "Svg");
            }
        }

        private ICommand _deleteCommand;
        public ICommand DeleteCommand
        {
            get
            {
                return this._deleteCommand ?? (this._deleteCommand = new DelegateCommand<ToolBoxCategory>(para => this.Delete(para)));
            }
        }

        private ICommand _addItemCommand;
        public ICommand AddCommand
        {
            get
            {
                return this._addItemCommand ?? (this._addItemCommand = new DelegateCommand(() => this.AddMyItem()));
            }
        }

        private ICommand _importItemCommand;
        public ICommand ImportItemCommand
        {
            get
            {
                return this._importItemCommand ?? (this._importItemCommand = new DelegateCommand(() => this.ImportMyItem()));
            }
        }

        private ICommand _deleteItemCommand;
        public ICommand DeleteItemCommand
        {
            get
            {
                return this._deleteItemCommand ?? (this._deleteItemCommand = new DelegateCommand<ToolBoxData>(para => this.DeleteMyItem(para)));
            }
        }

        public void Init()
        {
            ToolBoxCategory.Add(new MineToolBoxCategory() { Header = "我的形状", ToolBoxItems = new ObservableCollection<ToolBoxData>(), IsExpanded = true });

            List<ToolBoxData> toolBoxItems = new List<ToolBoxData>();
            toolBoxItems.Add(new ImageToolBoxData("../Images/Setting.png", typeof(SettingsDesignerItemViewModel), description: "致谢WPF-Diagram-Designer的开源作者，保留开源作品中的两个设计"));
            toolBoxItems.Add(new ImageToolBoxData("../Images/Persist.png", typeof(PersistDesignerItemViewModel), description: "致谢WPF-Diagram-Designer的开源作者，保留开源作品中的两个设计"));

            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "WPF-Diagram-Designer", ToolBoxItems = new ObservableCollection<ToolBoxData>(toolBoxItems), IsExpanded = true });


            List<ToolBoxData> defaultToolBoxItems = new List<ToolBoxData>();
            defaultToolBoxItems.Add(new TextToolBoxData("", typeof(DefaultDesignerItemViewModel)));
            var blockitem = new TextToolBoxData("Block", typeof(BlockDesignerItemViewModel), 64, 32, desiredMinSize: new Size(130, 65));       
            blockitem.ColorViewModel.FillColor.Color = Color.FromRgb(0x00, 0x2F, 0xA7);
            defaultToolBoxItems.Add(blockitem);
            var blockitem2 = new TextToolBoxData("Contain", typeof(BlockContainDesignerItemViewModel), 64, 32, desiredMinSize: new Size(130, 65));
            blockitem2.ColorViewModel.FillColor.Color = Color.FromRgb(0x00, 0x2F, 0xA7);
            defaultToolBoxItems.Add(blockitem2);
            var blockitem3 = new TextToolBoxData("ContainList", typeof(BlockContainListDesignerItemViewModel), 64, 32, desiredMinSize: new Size(130, 65));
            blockitem3.ColorViewModel.FillColor.Color = Color.FromRgb(0x00, 0x2F, 0xA7);
            defaultToolBoxItems.Add(blockitem3);

            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "Default", ToolBoxItems = new ObservableCollection<ToolBoxData>(defaultToolBoxItems), IsExpanded = true });

            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "Svg", ToolBoxItems = new ObservableCollection<ToolBoxData>() });

            List<PathToolBoxData> pathToolBoxItems = new List<PathToolBoxData>();
            pathToolBoxItems.Add(new PathToolBoxData("M 0,20 L 30 0 L 60,20 L 30,40 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0,0 H 60 V 40 C 30,30 30,50 0,40 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 10,0 L 60 0 L 50,40 L 0,40 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 10,20 A 20,20 0 1 1 50,20 A 20,20 0 1 1 10,20", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0, 3 C 30, -7 30, 13 60, 3 V 37 C 30, 47 30, 27 0, 37 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 50,0 V 40 M 10,0 V 40 M 0 0 H 60 V 40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 5,0 H 60 A 40,40 0 0 0 60,40 H 5 A 40,40 0 0 1 5,0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0,10 H 60 M 10,0 V 40 M 0,0 H 60 V 40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 30,40 A 20,20 0 1 1 30,0 A 20,20 0 0 1 43,35 H 50 L 50,40 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("F 1 M 57,40 H 3 A 4,20 0 1 1 3,0 H 57 A 4,20.1 0 1 1 56,0", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0 10 L 60,0 V 40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0 10 L 10,0 H 60 V 40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0,0 H 40 A 20,20 0 0 1 40,40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 20,40 A 20,20 0 0 1 20,0 H 40 A 20,20 0 0 1 40,40 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0,20 A 40,40 0 0 1 15,0 H 55 A 60,60 0 0 1 55,40 H 15 A 40,40, 0 0 1 0,20 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0 10 L 10,0 H 50 L 60,10 V 40 H 0 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0,20 L 10,0  H 50 L 60,20 L 50,40 H10 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.78 7.77L10 18.78l8.39-8.4a5.5 5.5 0 0 0-7.78-7.77l-.61.61z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 0 0 H 60 V 20 L 30, 40 L 0, 20 Z", typeof(PathItemViewModel)));
            pathToolBoxItems.Add(new PathToolBoxData("M 9,2 11,7 17,7 12,10 14,15 9,12 4,15 6,10 1,7 7,7 Z", typeof(PathItemViewModel)));
            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "Path", ToolBoxItems = new ObservableCollection<ToolBoxData>(pathToolBoxItems) });

            List<ToolBoxData> logicalChartToolBoxItems = new List<ToolBoxData>();
            logicalChartToolBoxItems.Add(new TextToolBoxData("0", typeof(ConstantDesignerItemViewModel), 32, 20));
            logicalChartToolBoxItems.Add(new TextToolBoxData("In", typeof(InputItemViewModel), 32, 20));
            logicalChartToolBoxItems.Add(new TextToolBoxData("Out", typeof(OutputItemViewModel), 32, 20));
            logicalChartToolBoxItems.Add(new EllipseTextToolBoxData("1s", typeof(TimerDesignerItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ADD", typeof(AddGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("SUB", typeof(SubtractGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("MUL", typeof(MultiplyGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("DIV", typeof(DivideGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("AVE", typeof(AverageGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("MOD", typeof(MODGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("AND", typeof(ANDGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("OR", typeof(ORGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("XOR", typeof(XORGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("NOT", typeof(NOTGateItemViewModel)));


            logicalChartToolBoxItems.Add(new TextToolBoxData("SHL", typeof(SHLGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("SHR", typeof(SHRGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ROL", typeof(ROLGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ROR", typeof(RORGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("SEL", typeof(SELGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("MAX", typeof(MAXGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("MIN", typeof(MINGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("LIMIT", typeof(LIMITGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("GT", typeof(GTGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("LT", typeof(LTGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("GE", typeof(GEGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("LE", typeof(LEGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("EQ", typeof(EQGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("NE", typeof(NEGateItemViewModel)));


            logicalChartToolBoxItems.Add(new TextToolBoxData("ABS", typeof(ABSGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("SQRT", typeof(SQRTGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("LN", typeof(LNGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("LOG", typeof(LOGGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("EXP", typeof(EXPGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("SIN", typeof(SINGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("COS", typeof(COSGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("TAN", typeof(TANGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ASIN", typeof(ASINGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ACOS", typeof(ACOSGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("ATAN", typeof(ATANGateItemViewModel)));
            logicalChartToolBoxItems.Add(new TextToolBoxData("EXPT", typeof(EXPTGateItemViewModel)));

            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "逻辑图", ToolBoxItems = new ObservableCollection<ToolBoxData>(logicalChartToolBoxItems) });

            List<ToolBoxData> flowchartToolBoxItems = new List<ToolBoxData>();
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.Start, typeof(StartFlowNode), 32, 32, new Size(80, 40)));
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.End, typeof(EndFlowNode), 32, 32, new Size(80, 40)));
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.Middle, typeof(MiddleFlowNode), 32, 32, new Size(80, 40)));
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.Decide, typeof(DecideFlowNode), 32, 32, new Size(80, 40)));
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.COBegin, typeof(COBeginFlowNode), 32, 32, new Size(80, 40))); ;
            flowchartToolBoxItems.Add(new FlowchartToolBoxData(NodeKinds.COEnd, typeof(COEndFlowNode), 32, 32, new Size(80, 40)));
            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "流程图", ToolBoxItems = new ObservableCollection<ToolBoxData>(flowchartToolBoxItems) });

            List<ToolBoxData> mediaToolBoxItems = new List<ToolBoxData>();
            mediaToolBoxItems.Add(new MediaToolBoxData("../Images/GIF.png", typeof(GifImageItemViewModel)));
            mediaToolBoxItems.Add(new MediaToolBoxData("../Images/VIDEO.png", typeof(VideoItemViewModel)));
            mediaToolBoxItems.Add(new MediaToolBoxData("../Images/SVG.png", typeof(SvgDesignerItemViewModel)));
            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "媒体", ToolBoxItems = new ObservableCollection<ToolBoxData>(mediaToolBoxItems) });

            List<ToolBoxData> sfcToolBoxItems = new List<ToolBoxData>();
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Start, typeof(SFCStartNode), 32, 28));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Condition, typeof(SFCConditionNode), 32, 28));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Node, typeof(SFCNodeNode), 32, 28));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Action, typeof(SFCActionNode), 32, 28));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.COBegin, typeof(SFCCOBeginNode), 32, 10));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.COEnd, typeof(SFCCOEndNode), 32, 10));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Simulate_Tank, typeof(Simulate_TankViewModel), 32, 32));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Simulate_Solenoid, typeof(Simulate_SolenoidViewModel)));
            sfcToolBoxItems.Add(new SFCToolBoxData(SFCNodeKinds.Simulate_Start, typeof(Simulate_StartViewModel)));
            ToolBoxCategory.Add(new ToolBoxCategory() { Header = "SFC顺序控制图", ToolBoxItems = new ObservableCollection<ToolBoxData>(sfcToolBoxItems) });

            LoadMyItems();
            LoadSvgItems();
        }

        private void Delete(ToolBoxCategory para)
        {
            para.IsChecked = false;
        }

        private string _svg = System.AppDomain.CurrentDomain.BaseDirectory + "Images\\Svgs";
        private void LoadSvgItems()
        {
            if (Directory.Exists(_svg))
            {
                var files = Directory.GetFiles(_svg);
                foreach (var filename in files.OrderBy(p => p, new NewNameHelper.NaturalStringComparer()).Where(p => p.ToLower().EndsWith(".svg")))
                {
                    SvgToolBoxCategory.ToolBoxItems.Add(new SvgToolBoxData(filename, typeof(SvgDesignerItemViewModel)));
                }
            }
        }

        private string _custom = System.AppDomain.CurrentDomain.BaseDirectory + "DesignItems\\Customs";

        private void LoadMyItems()
        {
            if (!Directory.Exists(_custom))
            {
                Directory.CreateDirectory(_custom);
            }

            if (Directory.Exists(_custom))
            {
                var files = Directory.GetFiles(_custom);
                foreach (var filename in files.Where(p => p.ToLower().EndsWith(".json")))
                {
                    AddMyItem(filename);
                }
            }
        }

        private object ReadMyItem(string filename)
        {
            try
            {
                var xmlobject = JsonConvert.DeserializeObject<DiagramDocument>(File.ReadAllText(filename));

                if (xmlobject.DiagramItems[0].DesignerItems.Count > 1)
                {
                    var itemBase = new MultipleDesignerItemToolBoxData(new SerializableObject() { DesignerItems = xmlobject.DiagramItems[0].DesignerItems, Connections = xmlobject.DiagramItems[0].Connections }, filename);

                    return itemBase;
                }
                else
                {
                    Type type = TypeHelper.GetType(xmlobject.DiagramItems[0].DesignerItems[0].SerializableTypeName);

                    var itemBase = JsonConvert.DeserializeObject(xmlobject.DiagramItems[0].DesignerItems[0].SerializableString, type) as DesignerItemBase;

                    return itemBase;
                }
            }
            catch
            {

            }

            return null;
        }

        private void AddMyItem()
        {
            if (_mainWindowViewModel?.PageViewModel?.DiagramViewModel != null)
            {
                DiagramDocument diagramDocument = new DiagramDocument();
                diagramDocument.DiagramItems = new List<DiagramItem>();
                DiagramItem diagramItem = new DiagramItem();

                var selectedDesignerItems = _mainWindowViewModel?.PageViewModel?.DiagramViewModel.SelectedItems.OfType<DesignerItemViewModelBase>();
                var selectedConnections = _mainWindowViewModel?.PageViewModel?.DiagramViewModel.SelectedItems.OfType<ConnectionViewModel>();

                diagramItem.DesignerItems = selectedDesignerItems.Select(p => p.ToSerializableItem(".json")).Where(p => p != null).ToList();
                diagramItem.Connections = selectedConnections.Select(p => p.ToSerializableItem(".json")).Where(p => p != null).ToList();

                diagramDocument.DiagramItems.Add(diagramItem);
                string newname = NewNameHelper.GetNewName(MyToolBoxCategory.ToolBoxItems.OfType<DesignerItemToolBoxData>().Select(p => Path.GetFileNameWithoutExtension(p.FileName)), "");
                var filename = $"{_custom}\\{newname}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(diagramDocument));

                AddMyItem(filename);
            }
        }

        private void AddMyItem(string filename)
        {
            try
            {
                var itemBase = ReadMyItem(filename);
                if (itemBase is DesignerItemBase designer)
                {
                    MyToolBoxCategory.ToolBoxItems.Add(new DesignerItemToolBoxData(designer, filename, TypeHelper.GetType(designer.ItemTypeName)));
                }
                else if (itemBase is MultipleDesignerItemToolBoxData multiple)
                {
                    MyToolBoxCategory.ToolBoxItems.Add(multiple);
                }
            }
            catch
            {

            }
        }

        private void ImportMyItem()
        {

        }

        private void DeleteMyItem(ToolBoxData toolBox)
        {
            MyToolBoxCategory.ToolBoxItems.Remove(toolBox);
            if (toolBox is DesignerItemToolBoxData designer)
            {
                File.Delete(designer.FileName);
            }
        }
    }

    public class MineToolBoxCategory : ToolBoxCategory
    {

    }
}
