using System;

using UnityEditor;
using UnityEngine;


namespace AIRuntime.Editor
{
    /// <summary>
    /// Dockable editor for the task selected in the AIRuntime Kanban board.
    /// </summary>
    public sealed class AIRuntimeKanbanTaskDetailsWindow :
        EditorWindow
    {
        [SerializeField]
        private string _taskId;

        [NonSerialized]
        private AIRuntimeKanbanSession _owner;


        internal static void Open(
            AIRuntimeKanbanSession owner,
            string taskId,
            string taskTitle)
        {
            AIRuntimeKanbanTaskDetailsWindow window =
                GetWindow<AIRuntimeKanbanTaskDetailsWindow>();

            window._owner =
                owner;

            window._taskId =
                taskId;

            window.titleContent =
                new GUIContent(
                    "Task Details",
                    taskTitle);

            window.minSize =
                new Vector2(
                    420,
                    320);

            window.Show();
            window.Focus();
            window.Repaint();
        }


        private void OnEnable()
        {
            titleContent =
                new GUIContent(
                    "Task Details");

            minSize =
                new Vector2(
                    420,
                    320);

            RecoverOwner();
        }


        private void OnGUI()
        {
            if (_owner == null)
            {
                RecoverOwner();
            }


            if (_owner == null)
            {
                EditorGUILayout.HelpBox(
                    "Open Window > AIRuntime > Kanban, then select a task card.",
                    MessageType.Info);

                return;
            }


            if (string.IsNullOrWhiteSpace(
                    _taskId))
            {
                EditorGUILayout.HelpBox(
                    "Select a task card from the Kanban board.",
                    MessageType.Info);

                return;
            }


            _owner.DrawTaskDetailsWindow(
                _taskId);
        }


        private void OnInspectorUpdate()
        {
            Repaint();
        }


        private void RecoverOwner()
        {
            AIRuntimeKanbanSession[] boards =
                Resources.FindObjectsOfTypeAll<AIRuntimeKanbanSession>();


            if (boards.Length > 0)
            {
                _owner =
                    boards[0];
            }
        }
    }
}
