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

namespace InABox.Wpf
{
    public class PostableSettingsGrid : DynamicItemsListGrid<PostableSettings>
    {
        public PostableSettingsGrid()
        {
            OnCustomiseEditor += PostableSettingsGrid_OnCustomiseEditor;
            OnEditorValueChanged += PostableSettingsGrid_OnEditorValueChanged;
        }

        private Dictionary<string, object?> PostableSettingsGrid_OnEditorValueChanged(object sender, string name, object value)
        {
            var editorForm = (IDynamicEditorForm)sender;
            if (name == nameof(PostableSettings.PosterType))
            {
                var editor = (editorForm.FindEditor(name) as LookupEditorControl)!;
                (editor.EditorDefinition as ComboLookupEditor)!.Buttons![0].SetEnabled(!string.IsNullOrWhiteSpace(value as string));
            }
            return new();
        }

        private void PostableSettingsGrid_OnCustomiseEditor(IDynamicEditorForm sender, PostableSettings[]? items, DynamicGridColumn column, BaseEditor editor)
        {
            var settings = items?.FirstOrDefault();
            if (settings is null) return;

            if(column.ColumnName == nameof(PostableSettings.PosterType) && editor is ComboLookupEditor combo)
            {
                var settingsButton = new EditorButton(settings, "Settings", 60, ViewSettings, false);
                settingsButton.SetEnabled(!string.IsNullOrWhiteSpace(settings.PosterType));
                combo.Buttons = new EditorButton[] { settingsButton };
            }
        }

        private void ViewSettings(object editor, object? item)
        {
            if (item is not PostableSettings settings) return;

            var entityType = CoreUtils.GetEntity(settings.PostableType);
            var posterType = CoreUtils.GetEntity(settings.PosterType!);
            var settingsType = posterType.GetInterfaceDefinition(typeof(IPoster<,>))!.GenericTypeArguments[1];

            var posterSettings = PosterUtils.LoadPosterSettings(entityType, settingsType);
            var grid = DynamicGridUtils.CreateDynamicGrid(typeof(PosterSettingsGrid<>), settingsType);
            if(grid.EditItems(new object[] { posterSettings }))
            {
                PosterUtils.SavePosterSettings(entityType, settingsType, posterSettings);
            }
        }
    }
}
