using System;
using System.Linq;

namespace InABox.Core
{
    //public abstract class LookupGenerator : Dictionary<object,String> { }

    public abstract class BaseComboEditor : StaticLookupEditor
    {
        protected ILookupGenerator? _generator;

        // [type] must be a class derived from LookupGenerator
        // with the values populated in the constructor
        public BaseComboEditor(Type generator) : base(generator)
        {
            if (!generator.GetInterfaces().Contains(typeof(ILookupGenerator)))
                throw new Exception(generator.EntityName() + " is not a valid Lookup Generator");
        }

        public event GenerateLookupsHandler? OnBeforeGenerateLookups;
        public event GenerateLookupsHandler? OnAfterGenerateLookups;

        public override CoreTable Values(string columnname, BaseObject[]? items = null)
        {
            var colname = columnname.Split('.').Last();
            _generator ??= (Activator.CreateInstance(Type, new object?[] { items }) as ILookupGenerator)!;
            _generator.OnBeforeGenerateLookups += OnBeforeGenerateLookups;
            _generator.OnAfterGenerateLookups += OnAfterGenerateLookups;
            return _generator.AsTable(colname);
        }

        public override void Clear()
        {
            _generator = null;
        }

        protected BaseComboEditor CloneBaseComboEditor()
        {
            var result = (CloneStaticLookupEditor() as BaseComboEditor)!;
            result.OnBeforeGenerateLookups = OnBeforeGenerateLookups;
            result.OnAfterGenerateLookups = OnAfterGenerateLookups;
            result._generator = _generator;
            return result;
        }
    }
}