using System;
using CycleGUI;

namespace StandardScene.Signal.Ui
{
    /// <summary>
    /// CycleGUI 独立窗口打开某一类 Model 列表（进程工具栏「打开机构/握手点/放行点列表」触发）。
    /// </summary>
    /// <remarks>
    /// 每种 T 共用一个静态窗口：已打开则前置，关掉后下次再 DeclarePanel。
    /// 真正的增删改在 <see cref="ModelTableEditor{T}"/>，保存直接写 JSON，
    /// 不自动 Reload 进程内 Worker，需再到进程上点「重新加载配置」。
    /// </remarks>
    public static class ModelListPanel<T> where T : class, new()
    {
        /// <summary>当前已声明的面板；关闭或异常后置 null，允许再次 Open。</summary>
        private static Panel _panel;

        private static readonly ModelTableEditor<T> Editor = new ModelTableEditor<T>();

        /// <param name="title">窗口标题。</param>
        /// <param name="path">JSON 绝对路径（应先经 SignalConfigStore.Resolve）。</param>
        /// <param name="keySelector">主键，添加/保存时查重（机构名、站点号等）。</param>
        public static void Open(string title, string path, Func<T, string> keySelector)
        {
            Editor.Bind(path, keySelector ?? (_ => ""), typeof(T).Name);

            if (_panel != null)
            {
                try { _panel.BringToFront(); return; }
                catch { _panel = null; }
            }

            var panel = GUI.DeclarePanel()
                .ShowTitle(title)
                .SetDefaultDocking(Panel.Docking.None)
                .InitSize(1100, 720)
                .InitPos(false, 0, 0, 0.5f, 0.5f, 0.5f, 0.5f);
            _panel = panel;
            panel.IfTerminalQuit(() => { if (_panel == panel) _panel = null; });

            panel.Define(pb =>
            {
                if (pb.Closing())
                {
                    panel.Exit();
                    _panel = null;
                    return;
                }

                Editor.Render(pb);
            });
        }
    }
}
