using InABox.Configuration;
using InABox.Core.Postable;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Text;

namespace InABox.Core
{
    public static class PosterUtils
    {

        #region Postable Settings

        private static PostableSettings FixPostableSettings(Type TPostable, PostableSettings settings)
        {
            if (string.IsNullOrWhiteSpace(settings.PostableType))
            {
                settings.PostableType = TPostable.EntityName();
            }
            return settings;
        }

        private static PostableSettings LoadPostableSettings(Type T)
        {
            return FixPostableSettings(T, new GlobalConfiguration<PostableSettings>(T.Name).Load());
        }

        public static PostableSettings LoadPostableSettings<T>()
            where T : Entity, IPostable
        {
            return LoadPostableSettings(typeof(T));
        }

        public static void SavePostableSettings<T>(PostableSettings settings)
            where T : Entity, IPostable
        {
            new GlobalConfiguration<PostableSettings>(typeof(T).Name).Save(FixPostableSettings(typeof(T), settings));
        }

        #endregion

        #region Poster Settings

        private static TSettings FixPosterSettings<TPostable, TSettings>(TSettings settings)
            where TPostable : IPostable
            where TSettings : PosterSettings, new()
        {
            if (string.IsNullOrWhiteSpace(settings.PostableType))
            {
                settings.PostableType = typeof(TPostable).EntityName();
            }
            return settings;
        }

        private static MethodInfo _loadPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
            .Where(x => x.Name == nameof(LoadPosterSettings) && x.IsGenericMethod)
            .Single();
        private static MethodInfo _savePosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
            .Where(x => x.Name == nameof(SavePosterSettings) && x.IsGenericMethod)
            .Single();

        public static TSettings LoadPosterSettings<TPostable, TSettings>()
            where TPostable : IPostable
            where TSettings : PosterSettings, new()
        {
            return FixPosterSettings<TPostable, TSettings>(new GlobalConfiguration<TSettings>(typeof(TPostable).Name).Load());
        }

        public static PosterSettings LoadPosterSettings(Type TPostable, Type TSettings)
        {
            return (_loadPosterSettingsMethod.MakeGenericMethod(TPostable, TSettings).Invoke(null, Array.Empty<object>()) as PosterSettings)!;
        }

        public static void SavePosterSettings<TPostable, TSettings>(TSettings settings)
            where TPostable : IPostable
            where TSettings : PosterSettings, new()
        {
            new GlobalConfiguration<TSettings>(typeof(TPostable).Name).Save(FixPosterSettings<TPostable, TSettings>(settings));
        }

        public static void SavePosterSettings(Type TPostable, Type TSettings, PosterSettings settings)
        {
            _savePosterSettingsMethod.MakeGenericMethod(TPostable, TSettings).Invoke(null, new object[] { settings });
        }

        #endregion

        #region Global Poster Settings

        private static MethodInfo _loadGlobalPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
            .Where(x => x.Name == nameof(LoadGlobalPosterSettings) && x.IsGenericMethod)
            .Single();
        private static MethodInfo _saveGlobalPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
            .Where(x => x.Name == nameof(SaveGlobalPosterSettings) && x.IsGenericMethod)
            .Single();

        public static IGlobalPosterSettings LoadGlobalPosterSettings(Type TGlobalSettings)
        {
            return (_loadGlobalPosterSettingsMethod.MakeGenericMethod(TGlobalSettings).Invoke(null, Array.Empty<object>()) as IGlobalPosterSettings)!;
        }
        public static TGlobalSettings LoadGlobalPosterSettings<TGlobalSettings>()
            where TGlobalSettings : BaseObject, IGlobalPosterSettings, new()
        {
            return new GlobalConfiguration<TGlobalSettings>().Load();
        }

        public static void SaveGlobalPosterSettings<TGlobalSettings>(TGlobalSettings settings)
            where TGlobalSettings : BaseObject, IGlobalPosterSettings, new()
        {
            new GlobalConfiguration<TGlobalSettings>().Save(settings);
        }

        public static void SaveGlobalPosterSettings(Type TGlobalSettings, IGlobalPosterSettings settings)
        {
            _saveGlobalPosterSettingsMethod.MakeGenericMethod(TGlobalSettings).Invoke(null, new object[] { settings });
        }

        #endregion

        #region Poster Engines

        private class EngineType
        {
            public Type Engine { get; set; }

            public Type Entity { get; set; }

            public Type Poster { get; set; }
        }

        private static EngineType[]? _posterEngines;
        private static Type[]? _posters = null;

        public static Type[] GetPosters()
        {
            _posters ??= CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.HasInterface(typeof(IPoster<,>))).ToArray();
            return _posters;
        }

        public static Type GetPoster(Type TPoster)
        {
            return GetPosters().Where(x => TPoster.IsAssignableFrom(x)).FirstOrDefault()
                ?? throw new Exception($"No poster of type {TPoster}.");
        }
        public static Type? GetPoster(string posterType)
        {
            return GetPosters()?.FirstOrDefault(x => x.EntityName() == posterType)!;
        }

        private static EngineType[] GetPosterEngines()
        {
            _posterEngines ??= CoreUtils.TypeList(
                AppDomain.CurrentDomain.GetAssemblies(),
                x => x.IsClass
                    && !x.IsAbstract
                    // Allow type-specific and generic engines
                    && x.GetTypeInfo().GenericTypeParameters.Length <= 1
                    && x.HasInterface(typeof(IPosterEngine<,,>))
            ).Select(x =>
            {
                var poster = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[1];
                return new EngineType
                {
                    Engine = x,
                    Entity = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[0],
                    Poster = poster.IsGenericType ? poster.GetGenericTypeDefinition() : poster
                };
            }).ToArray();
            return _posterEngines;
        }

        /// <summary>
        /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <paramref name="T"/>
        /// based on the current <see cref="PostableSettings"/> for <paramref name="T"/>.
        /// </summary>
        /// <returns></returns>
        public static Result<Type, Exception> GetEngine(Type T)
        {
            var settings = LoadPostableSettings(T);
            if (string.IsNullOrWhiteSpace(settings.PosterType))
            {
                return Result.Error<Exception>(new MissingSettingsException(T));
            }
            var poster = GetPoster(settings.PosterType);
            if(poster is null)
            {
                return Result.Error(new Exception($"No poster of type {settings.PosterType}."));
            }

            var engines = GetPosterEngines().Where(x =>
            {
                return x.Poster.IsInterface ? poster.HasInterface(x.Poster) : poster.IsSubclassOfRawGeneric(x.Poster);
            }).ToList();
            if (!engines.Any())
            {
                return Result.Error(new Exception("No poster for the given settings"));
            }
            else
            {
                var engineType = engines.Count == 1 ? engines[0] : engines.Single(x => x.Entity == T);

                if (engineType.Engine.IsGenericType)
                {
                    // If the engine is generic, we need to specify for the entity type.
                    return Result.Ok(engineType.Engine.MakeGenericType(T));
                }
                else
                {
                    // If the engine has already been specified for a given entity type, we just return the engine type straight up.
                    return Result.Ok(engineType.Engine);
                }
            }
        }

        /// <summary>
        /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <typeparamref name="T"/>
        /// based on the current <see cref="PostableSettings"/> for <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Type GetEngine<T>()
            where T : Entity, IPostable, IRemotable, IPersistent, new()
        {
            if (GetEngine(typeof(T)).Get(out var engineType, out var e))
            {
                return engineType;
            }
            else
            {
                throw e;
            }
        }

        public static IPosterEngine<T> CreateEngine<T>()
            where T : Entity, IPostable, IRemotable, IPersistent, new()
        {
            var engine = GetEngine<T>();
            return (Activator.CreateInstance(engine) as IPosterEngine<T>)!;
        }

        #endregion

        #region Auto-Refresh

        /// <summary>
        /// Check if <paramref name="item"/> needs to be reposted; if it does, <see cref="IPostable.PostedStatus"/> will be set to
        /// <see cref="PostedStatus.RequiresRepost"/> once this function is finished.
        /// </summary>
        /// <remarks>
        /// This will only do something if the currently set poster for this type has the <see cref="IAutoRefreshPoster{TEntity}"/> interface.
        /// </remarks>
        /// <typeparam name="T"></typeparam>
        /// <returns><see langword="true"/> if the item's status has been updated and needs to be reposted.</returns>
        public static bool CheckPostedStatus<T>(PostableSettings settings, T item)
            where T : BaseObject
        {
            if (!(item is IPostable postable))
            {
                return false;
            }
            if (postable.PostedStatus != PostedStatus.Posted || item?.HasOriginalValue(nameof(IPostable.PostedStatus)) == true)
            {
                return false;
            }

            settings = FixPostableSettings(typeof(T), settings);
            if (settings.PosterType.IsNullOrWhiteSpace())
            {
                return false;
            }
            var poster = GetPoster(settings.PosterType);
            if (poster is null)
            {
                return false;
            }
            var iautoRefresh = poster.GetInterfaceDefinition(typeof(IAutoRefreshPoster<,>));
            if(iautoRefresh != null)
            {
                var autoRefresher = Activator.CreateInstance(iautoRefresh.GenericTypeArguments[1]) as IAutoRefresher<T>;
                if (autoRefresher != null && autoRefresher.ShouldRepost(item!))
                {
                    postable.PostedStatus = PostedStatus.RequiresRepost;
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Process

        /// <summary>
        /// Process <paramref name="model"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>
        /// for <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T">The type of <paramref name="model"/> that needs to be processed.</typeparam>
        /// <param name="model"></param>
        /// <exception cref="EmptyPostException">If there are no items to post. In this case, nothing happens.</exception>
        /// <exception cref="RepostedException">If any of the <typeparamref name="T"/> have already been processed. In this case, nothing happens.</exception>
        /// <exception cref="MissingSettingsException">If the <see cref="PostableSettings"/> for <typeparamref name="T"/> do not exist.</exception>
        /// <exception cref="PostCancelledException">If the post has been cancelled by the user.</exception>
        /// <returns><see langword="null"/> if post was unsuccessful.</returns>
        /// 
        public static IPostResult<T>? Process<T>(IDataModel<T> model)
            where T : Entity, IPostable, IRemotable, IPersistent, new()
        {
            return CreateEngine<T>().Process(model);
        }

        /// <summary>
        /// Import <typeparamref name="T"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns><see langword="null"/> if post was unsuccessful.</returns>
        /// <exception cref="InvalidPullerException">If the engine is not a <see cref="IPullerEngine{TPostable,TPoster}"/></exception>
        public static IPullResult<T>? Pull<T>()
            where T : Entity, IPostable, IRemotable, IPersistent, new()
        {
            var engine = CreateEngine<T>();
            if(engine is IPullerEngine<T> puller)
            {
                return puller.Pull();
            }
            else
            {
                var intDef = engine.GetType().GetInterfaceDefinition(typeof(IPosterEngine<,,>));
                if(intDef != null)
                {
                    throw new InvalidPullerException(typeof(T), intDef.GenericTypeArguments[1]);
                }
                else
                {
                    throw new InvalidPullerException(typeof(T));
                }
            }
        }

        #endregion
    }
}
