using InABox.Core;
using InABox.DynamicGrid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Wpf.Dashboard.Editor;

internal class DynamicDashboardAdditionalTableEditItem : BaseObject
{
    [EditorSequence(1)]
    public string Name { get; set; } = "";

    [EditorSequence(2)]
    [ScriptEditor]
    public string Script { get; set; } = "";

    public DynamicDashboardAdditionalTableEditItem()
    {
    }

    public DynamicDashboardAdditionalTableEditItem(DynamicDashboardAdditionalTable table)
    {
        Name = table.Key;
        Script = table.Script ?? "";
    }

    public DynamicDashboardAdditionalTable ToTable()
    {
        return new DynamicDashboardAdditionalTable
        {
            Key = Name,
            Script = Script.IsNullOrWhiteSpace() ? null : Script
        };
    }
}

internal class DynamicDashboardAdditionalTableGrid : DynamicItemsListGrid<DynamicDashboardAdditionalTableEditItem>
{
    protected override void DoReconfigure(DynamicGridOptions options)
    {
        base.DoReconfigure(options);

        options.AddRows = true;
        options.EditRows = true;
        options.DeleteRows = true;
    }

    protected override void CustomiseEditor(IDynamicEditorForm form, DynamicDashboardAdditionalTableEditItem[] items, DynamicGridColumn column, BaseEditor editor)
    {
        base.CustomiseEditor(form, items, column, editor);

        var item = items[0];

        if(column.ColumnName == nameof(DynamicDashboardAdditionalTableEditItem.Script) && editor is ScriptEditor scriptEditor)
        {
            scriptEditor.Type = ScriptEditorType.TemplateEditor;
            scriptEditor.OnEditorClicked += () =>
            {
                var script = item.Script.NotWhiteSpaceOr()
                    ?? DynamicDashboardAdditionalTable.DefaultScript();

                var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
                if (editor.ShowDialog() == true)
                {
                    form.SetEditorValue(column.ColumnName, editor.Script);
                    item.Script = editor.Script;
                }
            };
        }
    }
}
