﻿using System;
using JLGames.RocketDriver.Actions.Service;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.Editor.Infra;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;

namespace JLGames.RocketDriver.Editor.Windows.Main.Service
{
    public class ServiceContentView : GraphView
    {
        public new class UxmlFactory : UxmlFactory<ServiceContentView, UxmlTraits>
        {
        }

        private ServiceSettings m_Settings;

        public Action<ServiceNodeView> OnNodeSelected;

        public ServiceContentView()
        {
            Insert(0, new GridBackground());

            this.AddManipulator(new ContentZoomer());
            this.AddManipulator(new ContentDragger());
            this.AddManipulator(new SelectionDragger());
            this.AddManipulator(new RectangleSelector());

            var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(MainEditorConfig.MainEditorUss);
            styleSheets.Add(styleSheet);
        }

        public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
        {
            var mousePos = evt.mousePosition;
            evt.menu.AppendAction($"Create Node", action => ShowGenNodePanel(mousePos));
            evt.menu.AppendAction($"Sort", action => SortNodes());
        }

        public void UpdateView(ServiceSettings settings)
        {
            if (null == settings || settings == m_Settings) return;

            m_Settings = settings;
            RefreshView();
        }

        private void RefreshView()
        {
            this.ClearElements();
            if (null == m_Settings) return;
            var list = m_Settings.SavedServices;
            if (null == list || list.Length == 0) return;
            foreach (var o in list)
            {
                GenNodeView(o);
            }
        }

        private void SortNodes()
        {
            DebugUtil.Log("节点排序，无选择排序全部，有选择排序选择的！");
        }

        private void ShowGenNodePanel(Vector2 defaultPostion)
        {
            GenNodeFromMenu(defaultPostion);
        }

        private void GenNodeFromMenu(Vector2 defaultPostion)
        {
            var node = ScriptableObject.CreateInstance<ServiceNode>();
            node.GenUid();
            node.SetPosition(defaultPostion);
            GenNodeView(node);
        }

        private void GenNodeView(ServiceNode node)
        {
            var nodeView = new ServiceNodeView(node);
            nodeView.OnNodeSelected = OnNodeSelected;
            AddElement(nodeView);
        }
    }
}