using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using AIStudio.Wpf.DiagramDesigner;
using AIStudio.Wpf.DiagramDesigner.Algorithms;
using AIStudio.Wpf.DiagramDesigner.Geometrys;
using AIStudio.Wpf.DiagramDesigner.Helpers;
using AIStudio.Wpf.Mind.ViewModels;

namespace AIStudio.Wpf.Mind.Helpers
{
    public class OrganizationalLayout : IMindLayout
    {
        public void Appearance(MindNode mindNode)
        {
            Appearance(mindNode, null, false);
        }

        public void Appearance(MindNode mindNode, MindThemeModel mindThemeModel, bool initAppearance)
        {
            switch (mindNode.NodeLevel)
            {
                case 0:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindThemeModel, initAppearance);

                            mindNode.ClearConnectors();
                            var port = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Bottom, true) { XRatio = 0.5, YRatio = 1 };
                            mindNode.AddConnector(port);
                        }
                        mindNode.ShapeViewModel.SinkMarker.PathStyle = ArrowPathStyle.None;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = ArrowSizeStyle.VerySmall;
                        mindNode.ConnectorOrientation = ConnectorOrientation.None;
                        break;
                    }
                case 1:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindThemeModel, initAppearance);

                            mindNode.ClearConnectors();
                            var port1 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Top, true) { XRatio = 0.5, YRatio = 0 };
                            mindNode.AddConnector(port1);
                            var port2 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Bottom, true) { XRatio = 0.5, YRatio = 1 };
                            mindNode.AddConnector(port2);
                        }

                        mindNode.ShapeViewModel.SinkMarker.PathStyle = ArrowPathStyle.None;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = ArrowSizeStyle.VerySmall;
                        mindNode.ConnectorOrientation = ConnectorOrientation.Top;
                        break;
                    }
                default:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindThemeModel, initAppearance);

                            mindNode.ClearConnectors();
                            var port1 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Top, true) { XRatio = 0.5, YRatio = 0 };
                            mindNode.AddConnector(port1);
                            var port2 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Bottom, true) { XRatio = 0.5, YRatio = 1 };
                            mindNode.AddConnector(port2);

                            mindNode.CornerRadius = new System.Windows.CornerRadius(0);
                            mindNode.BorderThickness = new System.Windows.Thickness(0, 0, 0, 0);
                        }
                        mindNode.ShapeViewModel.SinkMarker.PathStyle = ArrowPathStyle.None;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = ArrowSizeStyle.VerySmall;                     
                        mindNode.ConnectorOrientation = ConnectorOrientation.Top;
                        break;
                    }
            }
        }

        public ConnectionViewModel GetOrSetConnectionViewModel(MindNode source, MindNode sink, ConnectionViewModel connector = null)
        {
            if (source == null || sink == null)
                return null;

            if (connector == null)
            {
                connector = new ConnectionViewModel(source.Root, source.FirstConnector, sink.FirstConnector, DrawMode.ConnectingLineStraight, RouterMode.RouterOrthogonal);
            }
            else
            {
                connector?.UpdateConnectionMode(source.FirstConnector, sink.FirstConnector, DrawMode.ConnectingLineStraight.ToString(), RouterMode.RouterOrthogonal.ToString());
            }
            connector.ColorViewModel.LineColor = source.ColorViewModel.LineColor;           
            connector.ShapeViewModel.SinkMarker.PathStyle = source.ShapeViewModel.SinkMarker.PathStyle;
            connector.ShapeViewModel.SinkMarker.SizeStyle = sink.ShapeViewModel.SinkMarker.SizeStyle;
            connector.SetPathGeneratorParameter(smoothMargin: 20, smoothAutoSlope: 0.2, orthogonalShapeMargin: 2, orthogonalGlobalBoundsMargin: 5);

            return connector;
        }

        public void LayoutUpdated(MindNode mindNode)
        {
            if (mindNode == null) return;

            mindNode.GetLevel0Node().LayoutUpdating = true;
            var size = MeasureOverride(mindNode);
            ArrangeOverride(mindNode);

            mindNode.Root.BringToFrontCommand.Execute(new SelectableDesignerItemViewModelBase[] { mindNode });

            mindNode.GetLevel0Node().LayoutUpdating = false;
        }

        public SizeBase MeasureOverride(MindNode mindNode, bool isExpanded = true)
        {
            var sizewithSpacing = mindNode.SizeWithSpacing;
            if (mindNode.Children?.Count > 0)
            {
                var childrensizes = mindNode.Children.Select(p => MeasureOverride(p, mindNode.IsExpanded && isExpanded)).ToArray();
                sizewithSpacing = new SizeBase(Math.Max(sizewithSpacing.Width, childrensizes.SumOrDefault(p => p.Width)), sizewithSpacing.Height + childrensizes.MaxOrDefault(p => p.Height));
            }
            mindNode.DesiredSize = isExpanded ? sizewithSpacing : new SizeBase(0, 0);
            mindNode.Visible = isExpanded;

            return mindNode.DesiredSize;
        }

        public void ArrangeOverride(MindNode mindNode)
        {
            if (mindNode.NodeLevel == 0)
            {
                mindNode.DesiredPosition = mindNode.Position;
            }

            double left = mindNode.DesiredMiddlePosition.X - Math.Max(mindNode.DesiredSize.Width, mindNode.Children.SumOrDefault(p => p.DesiredSize.Width)) / 2;
            double top = mindNode.DesiredMiddlePosition.Y + mindNode.ItemHeight / 2 + mindNode.Spacing.Height;
            if (mindNode.Children?.Count > 0)
            {
                foreach (var child in mindNode.Children)
                {
                    child.Offset = new PointBase(child.Offset.X - child.RootNode.Offset.X, child.Offset.Y - child.RootNode.Offset.Y);//按根节点修正Offset
                    child.DesiredPosition = new PointBase(left + child.DesiredSize.Width / 2 - child.ItemWidth / 2, top + child.Spacing.Height);
                    child.Left = child.DesiredPosition.X + child.Offset.X;
                    child.Top = child.DesiredPosition.Y + child.Offset.Y;
                    left += child.DesiredSize.Width;

                    ArrangeOverride(child);

                    var connector = mindNode.Root?.Items.OfType<ConnectionViewModel>().FirstOrDefault(p => p.SourceConnectorInfo?.DataItem == mindNode && p.SinkConnectorInfoFully?.DataItem == child);
                    connector?.SetSourcePort(mindNode.BottomConnector);
                    connector?.SetSinkPort(child.TopConnector);
                    connector?.SetVisible(child.Visible);
                }

            }

            if (mindNode.NodeLevel == 0)
            {
                mindNode.Offset = new PointBase();//修正后归0
            }

        }
    }
}
