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

namespace InABox.Wpf.Grids
{
    public class PosterSettingsGrid<TPosterSettings> : DynamicItemsListGrid<TPosterSettings>
        where TPosterSettings : PosterSettings, new()
    {
        public PosterSettingsGrid()
        {
            OnCustomiseEditor += PosterSettingsGrid_OnCustomiseEditor;
        }

        private void PosterSettingsGrid_OnCustomiseEditor(IDynamicEditorForm sender, TPosterSettings[]? items, DynamicGridColumn column, BaseEditor editor)
        {
            if (items?.FirstOrDefault() is not TPosterSettings settings) return;

            if(column.ColumnName == nameof(PosterSettings.Script) && editor is ScriptEditor scriptEditor)
            {
                var tPostable = CoreUtils.GetEntity(settings.PostableType);

                scriptEditor.Type = ScriptEditorType.TemplateEditor;
                scriptEditor.OnEditorClicked += () =>
                {
                    var script = settings.Script.NotWhiteSpaceOr()
                        ?? settings.DefaultScript(tPostable);

                    var editor = new ScriptEditorWindow(script, SyntaxLanguage.CSharp);
                    if (editor.ShowDialog() == true)
                    {
                        sender.SetEditorValue(column.ColumnName, editor.Script);
                        settings.Script = editor.Script;
                        settings.ScriptEnabled = !settings.Script.IsNullOrWhiteSpace();
                        sender.SetEditorValue(nameof(PosterSettings.ScriptEnabled), settings.ScriptEnabled);
                    }
                };
            }
        }
    }
}
