using InABox.Clients;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace InABox.Core
{
    public interface ILookupDefinition
    {
        IFilter? DefineFilter();

        IColumns DefineColumns();

        IColumns RequiredColumns();

        ISortOrder? DefineSortOrder();

        string FormatLookup(Dictionary<string, object?> values, IEnumerable<string> exclude);
    }

    public interface ILookupDefinition<TLookup> : ILookupDefinition where TLookup : BaseObject, new()
    {
        new Filter<TLookup>? DefineFilter();

        new Columns<TLookup> DefineColumns();

        new Columns<TLookup> RequiredColumns();

        new SortOrder<TLookup>? DefineSortOrder();

        IFilter? ILookupDefinition.DefineFilter() => DefineFilter();

        IColumns ILookupDefinition.DefineColumns() => DefineColumns();

        IColumns ILookupDefinition.RequiredColumns() => RequiredColumns();

        ISortOrder? ILookupDefinition.DefineSortOrder() => DefineSortOrder();
    }

    public interface IEntityLookup<TLookup, TGenerator>
        where TGenerator : ILookupDefinition<TLookup>, new()
        where TLookup : BaseObject, new() { }

    public interface IChildEntityLookup<TParent, TChild, TGenerator>
        where TGenerator : LookupDefinitionGenerator<TChild, TParent>
        where TParent : class
        where TChild : class
    { }

    /// <summary>
    /// Define a lookup definition for a given property. The generator must derive from <see cref="LookupDefinitionGenerator{TLookup, TEntity}"/>.
    /// </summary>
    public class LookupDefinitionAttribute : Attribute
    {
        public Type Generator { get; set; }

        public LookupDefinitionAttribute(Type generator)
        {
            if (!generator.IsSubclassOfRawGeneric(typeof(LookupDefinitionGenerator<,>)))
            {
                throw new Exception($"{generator} is not a {typeof(LookupDefinitionGenerator<,>)}");
            }
            Generator = generator;
        }
    }

    public interface ILookupDefinitionGenerator
    {
        public IColumns DefineColumns();
        string FormatDisplay(CoreRow row);
        public IFilter? DefineFilter(BaseObject[] items);
        public IColumns DefineFilterColumns();
        public ISortOrder? DefineSortOrder();
        public void OnCreateItem(BaseObject[] parent, BaseObject lookup);
    }

    public abstract class LookupDefinitionGenerator<TLookup, TEntity> : ILookupDefinitionGenerator
        where TEntity: class
        where TLookup: class
    {
        public virtual Columns<TLookup> DefineColumns() => Columns.None<TLookup>();

        public virtual string FormatDisplay(CoreRow row) =>
            LookupFactory.FormatLookup<TLookup>(row.ToDictionary(), new string[] { "Display" });

        public virtual Filter<TLookup>? DefineFilter(TEntity[] items) => null;

        /// <summary>
        /// Define the columns required for the <c>items</c> parameter of <see cref="DefineFilter(TEntity[])"/>.
        /// </summary>
        /// <returns></returns>
        public virtual Columns<TEntity> DefineFilterColumns() => Columns.None<TEntity>();

        /// <summary>
        /// Customise an item created by a lookup editor.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="lookup"></param>
        public virtual void OnCreateItem(TEntity[] parent, TLookup lookup)
        {
        }

        public virtual SortOrder<TEntity>? DefineSortOrder() => null;

        void ILookupDefinitionGenerator.OnCreateItem(BaseObject[] parents, BaseObject lookup) => OnCreateItem(parents as TEntity[], lookup as TLookup);

        IColumns ILookupDefinitionGenerator.DefineColumns() => DefineColumns();

        string ILookupDefinitionGenerator.FormatDisplay(CoreRow row) => FormatDisplay(row);

        IFilter? ILookupDefinitionGenerator.DefineFilter(BaseObject[] items) => DefineFilter(items as TEntity[]);

        IColumns ILookupDefinitionGenerator.DefineFilterColumns() => DefineFilterColumns();

        ISortOrder? ILookupDefinitionGenerator.DefineSortOrder() => DefineSortOrder();
    }

    public static class LookupFactory
    {
        private static Dictionary<Type, Type>? _lookupDefinitions;

        private static readonly Dictionary<IProperty, Type> _lookupGenerators = new Dictionary<IProperty, Type>();

        private static readonly Dictionary<Tuple<Type, Type>, Type> _childGenerators = new Dictionary<Tuple<Type, Type>, Type>();

        public static void RegisterLookupGenerator<TEntity, TLookup, TLookupLink, TGenerator>(Expression<Func<TEntity, TLookupLink>> expression)
            where TGenerator : LookupDefinitionGenerator<TLookup, TEntity>
            where TLookupLink : IEntityLink<TLookup>
            where TLookup: class
            where TEntity: class
        {
            _lookupGenerators.TryAdd(DatabaseSchema.Property(typeof(TEntity), CoreUtils.GetFullPropertyName(expression, ".") + ".ID")!.Parent!, typeof(TGenerator));
        }
        public static void RegisterChildGenerator<TParent, TChild, TGenerator>()
            where TGenerator : LookupDefinitionGenerator<TChild, TParent>
            where TChild: class
            where TParent: class
        {
            _childGenerators.TryAdd(new Tuple<Type, Type>(typeof(TParent), typeof(TChild)), typeof(TGenerator));
        }

        private static ILookupDefinition? GetDefinition(Type T)
        {
            var type = T.GetInterfaceDefinition(typeof(IEntityLookup<,>))?.GenericTypeArguments[1];
            if(type is null)
            {
                _lookupDefinitions ??= CoreUtils.TypeList(x => !x.IsAbstract && !x.IsGenericType && x.HasInterface(typeof(ILookupDefinition<>)))
                    .Select(x => new Tuple<Type, Type>(x, x.GetInterfaceDefinition(typeof(ILookupDefinition<>))!))
                    .ToDictionary(x => x.Item2.GenericTypeArguments[0], x => x.Item1);
                type = _lookupDefinitions.GetValueOrDefault(T);
            }
            return type != null ? (Activator.CreateInstance(type) as ILookupDefinition) : null;
        }

        private static IProperty? GetLinkProperty(Type T, string column)
        {
            if (column.EndsWith(".ID"))
            {
                var property = DatabaseSchema.Property(T, column);
                if(property?.Parent?.IsEntityLink == true)
                {
                    return property.Parent;
                }
            }
            return DatabaseSchema.Property(T, $"{column}.{nameof(IEntityLink.ID)}")?.Parent;
        }

        private static ILookupDefinitionGenerator? GetLookupGenerator(IProperty? property)
        {
            var generator = property?.GetAttribute<LookupDefinitionAttribute>()?.Generator
                ?? (property != null ? _lookupGenerators.GetValueOrDefault(property) : null);
            return generator != null
                ? Activator.CreateInstance(generator) as ILookupDefinitionGenerator
                : null;
        }
        
        public static ILookupDefinitionGenerator? GetLookupGenerator(Type T, string column)
        {
            return GetLookupGenerator(GetLinkProperty(T, column));
        }
        private static ILookupDefinitionGenerator? GetChildGenerator(Type TParent, Type TChild)
        {
            var generator = TParent.GetInterfaces(typeof(IChildEntityLookup<,,>))
                .FirstOrDefault(x => x.GenericTypeArguments[0] == TParent && x.GenericTypeArguments[1] == TChild)?.GenericTypeArguments[2]
                ?? _childGenerators.GetValueOrDefault(new Tuple<Type, Type>(TParent, TChild));
            return generator != null ? Activator.CreateInstance(generator) as ILookupDefinitionGenerator : null;
        }

        #region Non-generic functions

        /// <summary>
        /// Define a generic filter for <paramref name="TLookup"/>, not in the context of a parent object. For use in multi-select windows and stuff.
        /// </summary>
        /// <param name="TLookup"></param>
        /// <returns></returns>
        public static IFilter? DefineFilter(Type TLookup)
        {
            return GetDefinition(TLookup)?.DefineFilter();
        }

        /// <summary>
        /// Define a specific filter for <paramref name="TLookup"/> in the context of (one or more) <paramref name="TEntity"/>,
        /// specifically for property <paramref name="column"/>, which should be an <see cref="IEntityLink"/> or the ID property of an <see cref="IEntityLink"/>.
        /// This is the standard function for lookups.
        /// </summary>
        /// <remarks>
        /// <paramref name="column"/> can either be the name of an entity link, or the ID property of that entity link.
        /// </remarks>
        /// <param name="TEntity"></param>
        /// <param name="TLookup"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static IFilter? DefineLookupFilter(Type TEntity, Type TLookup, string column, BaseObject[] items)
        {
            var generator = GetLookupGenerator(TEntity, column);
            var filter = generator?.DefineFilter(items);
            return filter ?? GetDefinition(TLookup)?.DefineFilter();
        }

        /// <summary>
        /// Define a specific filter for <paramref name="TLookup"/> in the context of (one or more) <paramref name="TEntity"/>,
        /// specifically for child entities.
        /// </summary>
        /// <param name="TEntity"></param>
        /// <param name="TLookup"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static IFilter? DefineChildFilter(Type TEntity, Type TLookup, BaseObject[] items)
        {
            var generator = GetChildGenerator(TEntity, TLookup);
            var filter = generator?.DefineFilter(items);
            return filter ?? GetDefinition(TLookup)?.DefineFilter();
        }

        /// <summary>
        /// Define the columns needed for the entities for <see cref="DefineLookupFilter(Type, Type, string, BaseObject[])"/>.
        /// </summary>
        /// <param name="TEntity"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static IColumns DefineLookupFilterColumns(Type TEntity, string column)
        {
            return GetLookupGenerator(TEntity, column)?.DefineFilterColumns() ?? Columns.None(TEntity);
        }

        /// <summary>
        /// Define the columns needed for the entities for <see cref="DefineChildFilter(Type, Type BaseObject[])"/>.
        /// </summary>
        /// <param name="TEntity"></param>
        /// <returns></returns>
        public static IColumns DefineChildFilterColumns(Type TEntity, Type TLookup)
        {
            return GetChildGenerator(TEntity, TLookup)?.DefineFilterColumns() ?? Columns.None(TEntity);
        }

        /// <summary>
        /// Define a generic set of columns for <paramref name="TLookup"/>, not in the context of a parent object. For use in multi-select windows and stuff.
        /// </summary>
        /// <param name="TLookup"></param>
        /// <returns></returns>
        public static IColumns DefineColumns(Type TLookup)
        {
            return GetDefinition(TLookup)?.DefineColumns() ?? Columns.Create(TLookup, ColumnTypeFlags.IncludeID | ColumnTypeFlags.IncludeVisible);
        }

        /// <summary>
        /// Get a list of columns that need to be loaded in a lookup for children of <paramref name="TLookup"/> on <paramref name="TEntity"/>.
        /// </summary>
        /// <param name="TEntity"></param>
        /// <param name="TLookup"></param>
        /// <returns></returns>
        public static IColumns DefineChildColumns(Type TEntity, Type TLookup)
        {
            var columns = Columns.None(TLookup);

            foreach(var prop in DatabaseSchema.Properties(TLookup).Where(x => x.Required))
            {
                columns.Add(prop.Name);
            }

            // Add any columns defined on a LookupDefinitionAttribute
            var generator = GetChildGenerator(TEntity, TLookup);
            if(generator != null)
            {
                foreach (var prop in generator.DefineColumns())
                {
                    columns.Add(prop);
                }
            }

            // Finally, add any columns defined on an ILookupDefinition for this entity.
            if(GetDefinition(TLookup) is ILookupDefinition definition)
            {
                foreach(var prop in definition.DefineColumns())
                {
                    columns.Add(prop);
                }
            }

            return columns;
        }

        /// <summary>
        /// Get a list of columns that need to be loaded in a lookup for property <paramref name="column"/> on <paramref name="TEntity"/>.
        /// </summary>
        /// <remarks>
        /// <paramref name="column"/> can either be the name of an entity link, or the ID property of that entity link.<br/>
        /// Gives an aggregate of required columns on the entity link in question, the linked properties of <paramref name="TEntity"/>, and any defined on
        /// a <see cref="LookupDefinitionAttribute"/> or <see cref="ILookupDefinition"/>.
        /// </remarks>
        /// <param name="TEntity"></param>
        /// <param name="TLookup"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static IColumns DefineLookupColumns(Type TEntity, Type TLookup, string column)
        {
            var columns = Columns.None(TLookup);
            
            var property = GetLinkProperty(TEntity, column);
            if(property != null)
            {
                var prefix = property.Name + ".";

                // Add all required columns of the entity link.
                foreach(var prop in DatabaseSchema.Properties(TEntity).Where(x => x.Required && x.Name.StartsWith(prefix)))
                {
                    columns.Add(prop.Name[prefix.Length..]);
                }

                // Add all columns which are associated with linked properties.
                foreach(var lProp in LinkedProperties.FindAll(TEntity).Where(x => x.Path.StartsWith(prefix)))
                {
                    var parent = lProp.Path[prefix.Length..];
                    columns.Add((parent.IsNullOrWhiteSpace() ? "" : $"{parent}.") + lProp.Source);
                }

                // Add any columns defined on a LookupDefinitionAttribute
                var generator = GetLookupGenerator(property);
                if(generator != null)
                {
                    foreach (var prop in generator.DefineColumns())
                    {
                        columns.Add(prop);
                    }
                }
            }

            // Finally, add any columns defined on an ILookupDefinition for this entity.
            if(GetDefinition(TLookup) is ILookupDefinition definition)
            {
                foreach(var prop in definition.DefineColumns())
                {
                    columns.Add(prop);
                }
            }
            if (columns.Count == 0)
            {
                columns = Columns.Create(TLookup, ColumnTypeFlags.IncludeID | ColumnTypeFlags.IncludeVisible);
            }
            else
            {
                columns.Add(nameof(Entity.ID));
            }

            return columns;
        }

        /// <summary>
        /// Get a list of columns that need to be loaded for an entity of type <paramref name="T"/>.
        /// </summary>
        /// <remarks>
        /// Gives an aggregate of required columns, and columns found on <see cref="LookupDefinitionAttribute"/> and <see cref="ILookupDefinition"/>.
        /// </remarks>
        /// <param name="T"></param>
        /// <returns></returns>
        public static IColumns RequiredColumns(Type T)
        {
            var result = Columns.None(T);

            var props = DatabaseSchema.Properties(T);
            foreach (var prop in DatabaseSchema.Properties(T))
            {
                if (prop.Required)
                {
                    // First, add all the required properties, as calculated by DatabaseSchema.
                    result.Add(prop.Name);
                }
                else if(prop.Name.EndsWith(".ID"))
                {
                    // We also want to load columns on lookup definitions, which are attributes on entity link classes.
                    // EntityLinks must have an ID property, so we use that to ensure we only get one property from the entity link,
                    // since we actually care about the parent.
                    var parentLink = prop.GetOuterParent(x => x.IsEntityLink);
                    if(parentLink != null && parentLink == prop.Parent)
                    {
                        // We need here to ensure that the outermost parent link is the parent of this property, otherwise we're multiple nested entitylinks deep,
                        // and we don't want that.
                        if(parentLink.GetAttribute<LookupDefinitionAttribute>() is LookupDefinitionAttribute attr)
                        {
                            foreach (var column in (Activator.CreateInstance(attr.Generator) as ILookupDefinitionGenerator)!.DefineColumns())
                            {
                                result.Add(parentLink.Name + "." + column.Property);
                            }
                        }
                    }
                }
            }

            // We also need to load all the columns defined on lookup definitions; if we've defined it on a lookup,
            // it means it's probably necessary for a calculation of some kind, and therefore we should also have it when we load the object.
            if(GetDefinition(T) is ILookupDefinition definition)
            {
                foreach(var column in definition.RequiredColumns())
                {
                    result.Add(column);
                }
            }

            return result;
        }

        public static string DefaultFormatLookup(Dictionary<string, object?> values, IEnumerable<string> exclude)
        {
            return string.Join(": ",
                values.Where(x => x.Value != null && x.Value.GetType() != typeof(Guid) && (exclude == null || !exclude.Contains(x.Key)))
                    .Select(p => p.Value));
        }

        public static string FormatLookup(Type T, Dictionary<string, object?> values, IEnumerable<string> exclude)
        {
            if(GetDefinition(T) is ILookupDefinition definition)
            {
                return definition.FormatLookup(values, exclude);
            }
            return DefaultFormatLookup(values, exclude);
        }

        public static string FormatLookup(Type TEntity, Type TLookup, CoreRow row, string column)
        {
            var generator = GetLookupGenerator(TEntity, column);
            if(generator != null)
            {
                return generator.FormatDisplay(row);
            }
            else
            {
                return FormatLookup(TLookup, row.ToDictionary(new[] { "Display" }), Array.Empty<string>());
            }
        }

        public static ISortOrder? DefineSort(Type T)
        {
            return GetDefinition(T)?.DefineSortOrder();
        }

        public static void OnCreateItem(Type TEntity, string column, BaseObject[] items, BaseObject item)
        {
            var generator = GetLookupGenerator(TEntity, column);
            generator?.OnCreateItem(items, item);
        }

        #endregion

        #region Generic Wrappers

        public static Filter<TLookup> DefineFilter<TLookup>()
            => (DefineFilter(typeof(TLookup)) as Filter<TLookup>)!;

        public static Filter<TLookup>? DefineChildFilter<TEntity, TLookup>(TEntity[] items)
            where TEntity : BaseObject
            => (DefineChildFilter(typeof(TEntity), typeof(TLookup), items) as Filter<TLookup>)!;

        public static Filter<TLookup>? DefineLookupFilter<TEntity, TLookup, TLookupLink>(Expression<Func<TEntity, TLookupLink>> column, TEntity[] items)
            where TLookupLink : IEntityLink<TLookup>
            where TEntity : BaseObject
            => (DefineLookupFilter(typeof(TEntity), typeof(TLookup), CoreUtils.GetFullPropertyName(column, "."), items) as Filter<TLookup>)!;

        public static Columns<TEntity> DefineChildFilterColumns<TEntity, TLookup>()
            => (DefineChildFilterColumns(typeof(TEntity), typeof(TLookup)) as Columns<TEntity>)!;

        public static Columns<TEntity> DefineLookupFilterColumns<TEntity, TLookup, TLookupLink>(Expression<Func<TEntity, TLookupLink>> column)
            where TLookupLink : IEntityLink<TLookup>
            => (DefineLookupFilterColumns(typeof(TEntity), CoreUtils.GetFullPropertyName(column, ".")) as Columns<TEntity>)!;

        public static Columns<TLookup> DefineColumns<TLookup>()
            => (DefineColumns(typeof(TLookup)) as Columns<TLookup>)!;

        public static Columns<TLookup> DefineChildColumns<TEntity, TLookup>()
            => (DefineChildColumns(typeof(TEntity), typeof(TLookup)) as Columns<TLookup>)!;

        public static Columns<TLookup> DefineLookupColumns<TEntity, TLookup, TLookupLink>(Expression<Func<TEntity, TLookupLink>> column)
            where TLookupLink : IEntityLink<TLookup>
            => (DefineLookupColumns(typeof(TEntity), typeof(TLookup), CoreUtils.GetFullPropertyName(column, ".")) as Columns<TLookup>)!;

        public static Columns<TLookup> RequiredColumns<TLookup>()
            => (RequiredColumns(typeof(TLookup)) as Columns<TLookup>)!;

        public static SortOrder<TLookup>? DefineSort<TLookup>() => DefineSort(typeof(TLookup)) as SortOrder<TLookup>;

        public static string FormatLookup<T>(Dictionary<string, object?> values, IEnumerable<string> exclude) => FormatLookup(typeof(T), values, exclude);

        public static string FormatLookup<TEntity, TLookup, TLookupLink>(CoreRow row, Expression<Func<TEntity, TLookupLink>> column)
            where TLookupLink : IEntityLink<TLookup>
            => FormatLookup(typeof(TEntity), typeof(TLookup), row, CoreUtils.GetFullPropertyName(column, "."));

        public static void OnCreateItem<TEntity, TLookup, TLookupLink>(Expression<Func<TEntity, TLookupLink>> column, TEntity[] items, TLookup item)
            where TLookupLink : IEntityLink<TLookup>
            where TEntity : BaseObject
            where TLookup : BaseObject
            => OnCreateItem(typeof(TEntity), CoreUtils.GetFullPropertyName(column, "."), items, item);

        public static void DoLookup<TEntity, TLookup, TLookupLink>(TEntity entity, Expression<Func<TEntity, TLookupLink>> column, Guid lookupID)
            where TEntity : class
            where TLookup : Entity, IRemotable, IPersistent, new()
            where TLookupLink : IEntityLink<TLookup>
        {
            if(lookupID == Guid.Empty)
            {
                return;
            }
            var columns = DefineLookupColumns<TEntity, TLookup, TLookupLink>(column);
            var row = Client.Query(new Filter<TLookup>(x => x.ID).IsEqualTo(lookupID), columns).Rows.FirstOrDefault();
            if(row is null)
            {
                Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in DoLookup: {typeof(TLookup).Name} with ID {lookupID} not found.");
                return;
            }

            foreach(var subColumn in columns)
            {
                CoreUtils.SetPropertyValue(entity, CoreUtils.GetFullPropertyName(column, ".") + "." + subColumn.Property, row[subColumn.Property]);
            }
        }

        public static void DoLookups<TEntity, TLookup, TLookupLink>(IEnumerable<Tuple<TEntity, Guid>> lookups, Expression<Func<TEntity, TLookupLink>> column)
            where TEntity : class
            where TLookup : Entity, IRemotable, IPersistent, new()
            where TLookupLink : IEntityLink<TLookup>
        {
            lookups = lookups.AsIList();
            var lookupIDs = lookups.Select(x => x.Item2).Where(x => x != Guid.Empty).ToArray();

            var columns = DefineLookupColumns<TEntity, TLookup, TLookupLink>(column).Add(x => x.ID);
            var data = Client.Query(new Filter<TLookup>(x => x.ID).InList(lookupIDs), columns).Rows.ToDictionary(x => x.Get<TLookup, Guid>(x => x.ID));

            foreach(var (entity, lookupID) in lookups)
            {
                if(lookupID == Guid.Empty)
                {
                    continue;
                }

                if(!data.TryGetValue(lookupID, out var row))
                {
                    Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in DoLookup: {typeof(TLookup).Name} with ID {lookupID} not found.");
                    continue;
                }

                foreach(var subColumn in columns)
                {
                    CoreUtils.SetPropertyValue(entity, CoreUtils.GetFullPropertyName(column, ".") + "." + subColumn.Property, row[subColumn.Property]);
                }
            }
        }

        #endregion
    }

    public abstract class BaseObjectLookup<TLookup> : ILookupDefinition<TLookup> where TLookup : BaseObject, new()
    {
        public virtual string FormatLookup(Dictionary<string, object?> values, IEnumerable<string> exclude)
        {
            var filtered = new Dictionary<string, object?>();
            var cols = DefineColumns();
            foreach (var col in cols)
                if (values.ContainsKey(col.Property) && values[col.Property] != null && values[col.Property]?.GetType() != typeof(Guid))
                    filtered[col.Property] = values[col.Property];
            return LookupFactory.DefaultFormatLookup(filtered, exclude);
        }

        public abstract Columns<TLookup> DefineColumns();

        public abstract Columns<TLookup> RequiredColumns();

        public abstract Filter<TLookup>? DefineFilter();

        public abstract SortOrder<TLookup>? DefineSortOrder();
    }

    public abstract class EntityLookup<TLookup> : BaseObjectLookup<TLookup> where TLookup : Entity, new()
    {
        public override Columns<TLookup> DefineColumns()
        {
            return new Columns<TLookup>(ColumnTypeFlags.IncludeID);
        }

        public override Columns<TLookup> RequiredColumns()
        {
            return Columns.None<TLookup>();
        }
    }
}