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

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

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

        public void PushToAll<TPush>(TPush push) where TPush : BaseObject
        {
            ClientFactory.PushHandlers.Push(typeof(TPush), push);
        }

        public void PushToSession<TPush>(Guid session, TPush push) where TPush : BaseObject
            => PushToSession(session, typeof(TPush), push);

        public void PushToSession(Guid session, Type TPush, BaseObject push)
        {
            if (session == ClientFactory.SessionID)
            {
                ClientFactory.PushHandlers.Push(TPush, push);
            }
        }
    }

    public class LocalClient<TEntity> : BaseClient<TEntity> where TEntity : Entity, new()
    {
        public LocalClient()
        {
            var pusher = new LocalPusher();
            PushManager.AddPusher(pusher);
            PushManager.Poll(ClientFactory.SessionID);
        }
        
        public override bool IsConnected() => true;

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

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

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

        protected override IValidationData 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 IValidationData DoValidate(Filter<User> filter, Guid session = default)
        {
            var row = DbFactory.FindStore<User>(Guid.Empty, "", ClientFactory.Platform, ClientFactory.Version, Logger.New()).Query(
                filter,
                Columns.None<User>().Add(x => x.ID, x => x.UserID, x => x.SecurityGroup.ID, x => x.Recipient2FA)
            ).Rows.FirstOrDefault();
            if (row != null)
            {
                return new ValidationData(
                    ValidationStatus.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(
                ValidationStatus.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, CoreRange? range = null )
        {
            var store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version, Logger.New());
            var result = store.Query(filter, columns, sort, range);
            return result;
        }

        #endregion

        #region Load

        protected override TEntity[] DoLoad(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
        {
            var store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version, Logger.New());
            var result = store.Query(filter, null, sort, range).ToObjects<TEntity>().ToArray();
            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, Logger.New());
        }

        #endregion

        #region Save

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

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

        #endregion

        #region Delete

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

        protected override void DoDelete(IEnumerable<TEntity> entities, string auditnote)
        {
            var store = DbFactory.FindStore<TEntity>(ClientFactory.UserGuid, ClientFactory.UserID, ClientFactory.Platform, ClientFactory.Version, Logger.New());
            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,
                DatabaseID = DbFactory.ID
            };

        }

        #endregion

        #region Update

        public override string Version()
        {
            return File.ReadAllText(Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update/version.txt"));
        }

        public override string ReleaseNotes()
        {
            return File.ReadAllText(Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update/Release Notes.txt"));
        }

        public override byte[]? Installer()
        {
            return File.ReadAllBytes(Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update/PRSDesktopSetup.exe"));
        }

        #endregion
    }
}