using InABox.Core;
using InABox.Database;
using InABox.WebSocket.Shared;

namespace InABox.Clients
{
    class LocalNotifier : Notifier
    {
        protected override IEnumerable<Guid> GetUserSessions(Guid userID)
        {
            if(userID == ClientFactory.UserGuid)
            {
                return new Guid[] { ClientFactory.SessionID };
            }
            return Array.Empty<Guid>();
        }

        protected override IEnumerable<Guid> GetSessions(Platform platform)
        {
            if (platform == Platform.Desktop)
            {
                return new Guid[] { ClientFactory.SessionID };
            }
            return Array.Empty<Guid>();
        }

        protected override void NotifyAll<TNotification>(TNotification notification)
        {
            ClientFactory.Notifications.Notify(typeof(TNotification), notification);
        }

        protected override void NotifySession<TNotification>(Guid session, TNotification notification) =>
            NotifySession(session, typeof(TNotification), notification);

        protected override void NotifySession(Guid session, Type TNotification, object? notification)
        {
            if (session == ClientFactory.SessionID)
            {
                ClientFactory.Notifications.Notify(TNotification, notification);
            }
        }
    }

    public class LocalClient<TEntity> : BaseClient<TEntity> where TEntity : Entity, new()
    {
        private IStore<TEntity> store;

        public LocalClient(string parameters)
        {
            Notify.Notifier = new LocalNotifier();
            Notify.Notifier.Poll(ClientFactory.SessionID);
        }

        public override IEnumerable<string> SupportedTypes()
        {
            return DbFactory.SupportedTypes();
        }

        protected override ValidationData DoValidate(Guid session)
        {
            return DoValidate(new Filter<User>().None(), session);
        }

        protected override ValidationData DoValidate(string pin, Guid session)
        {
            return DoValidate(
                new Filter<User>(x => x.PIN).IsEqualTo(pin), session);
        }

        protected override ValidationData DoValidate(string userid, string password, Guid session)
        {
            return DoValidate(
                new Filter<User>(x => x.UserID).IsEqualTo(userid)
                    .And(x => x.Password).IsEqualTo(password), session);
        }

        private ValidationData DoValidate(Filter<User> filter, Guid session = default)
        {
            var row = DbFactory.FindStore<User>(Guid.Empty, "", ClientFactory.Platform, ClientFactory.Version).Query(
                filter,
                new Columns<User>(x => x.ID, x => x.UserID, x => x.SecurityGroup.ID, x => x.Recipient2FA)
            ).Rows.FirstOrDefault();
            if (row != null)
            {
                return new ValidationData(
                    ValidationResult.VALID,
                    row.Get<User, string>(x => x.UserID),
                    row.Get<User, Guid>(x => x.ID),
                    row.Get<User, Guid>(x => x.SecurityGroup.ID),
                    Guid.Empty,
                    row.Get<User, string?>(x => x.Recipient2FA),
                    DateTime.MinValue
                );
            }

            return new ValidationData(
                ValidationResult.INVALID,
                "",
                Guid.Empty,
                Guid.Empty,
                Guid.Empty,
                null,
                DateTime.MinValue
            );
        }

        #region Query

        protected override CoreTable DoQuery(Filter<TEntity> filter, Columns<TEntity> columns, SortOrder<TEntity> sort = null)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            var result = store.Query(filter, columns, sort);
            return result;
        }

        #endregion

        #region Load

        protected override TEntity[] DoLoad(Filter<TEntity> filter = null, SortOrder<TEntity> sort = null)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            var result = store.Load(filter, sort);
            return result;
        }

        #endregion

        #region MultipleTables

        protected override Dictionary<string, CoreTable> DoQueryMultiple(Dictionary<string, IQueryDef> queries)
        {
            return DbFactory.QueryMultiple(queries, ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
        }

        #endregion

        #region List

        //public override IEnumerable<object[]> List(Filter<TEntity> filter = null, Columns<TEntity> columns = null, SortOrder<TEntity> sort = null)
        //{
        //    store = DbFactory.FindStore<TEntity>(UserID, Password, Platform, Version);
        //    return store.List(filter, columns, sort);
        //    //DataTable result = LoadDataTable(columns, data);
        //    //return result;
        //}

        //public override IEnumerable<object[]> List(object filter = null, object columns = null, object sort = null)
        //{
        //    store = DbFactory.FindStore<TEntity>(UserID, Password, Platform, Version);
        //    return List((Filter<TEntity>)filter, (Columns<TEntity>)columns, (SortOrder<TEntity>)sort);
        //    //return result;
        //}

        //public override void List(Filter<TEntity> filter, Columns<TEntity> columns, SortOrder<TEntity> sort, Action<IEnumerable<object[]>, Exception> callback)
        //{
        //    Task.Run(() =>
        //    {
        //        try
        //        {
        //            IEnumerable<object[]> result = List(filter, columns, sort);
        //            callback.Invoke(result, null);
        //        }
        //        catch (Exception e)
        //        {
        //            callback.Invoke(null, e);
        //        }

        //    }
        //    );
        //}

        #endregion

        #region Save

        protected override void DoSave(TEntity entity, string auditnote)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            store.Save(entity, auditnote);
        }

        protected override void DoSave(IEnumerable<TEntity> entities, string auditnote)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            store.Save(entities, auditnote);
        }

        #endregion

        #region Delete

        protected override void DoDelete(TEntity entity, string auditnote)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            store.Delete(entity, auditnote);
        }

        protected override void DoDelete(IList<TEntity> entities, string auditnote)
        {
            store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version);
            store.Delete(entities, auditnote);
        }

        #endregion

        #region 2FA

        protected override bool DoCheck2FA(string code, Guid? session)
        {
            return true;
        }

        #endregion

        #region Ping

        protected override bool DoPing()
        {
            return true;
        }

        public override DatabaseInfo Info()
        {
            return new DatabaseInfo()
            {
                Version = CoreUtils.GetVersion(),
                ColorScheme = DbFactory.ColorScheme,
                Logo = DbFactory.Logo
            };

        }

        #endregion
    }
}