using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using InABox.Core;

namespace InABox.Clients
{
    public abstract class BaseClient<TEntity> : IClient<TEntity>, IClient where TEntity : Entity, new()
    {
        public BaseClient()
        {
            Timeout = new TimeSpan(0, 1, 0);
        }

        //public abstract string UserID { get; set; }
        //public abstract string Password { get; set; }
        //public abstract string Platform { get; set; }
        //public abstract string Version { get; set; }

        public TimeSpan Timeout { get; set; }

        public abstract IEnumerable<string> SupportedTypes();

        public event LogEvent OnLog;

        public void Log(string format, params object[] parameters)
        {
            OnLog?.Invoke(this, string.Format(format, parameters));
        }

        //public abstract void Delete(TEntity entity, string auditnote);
        //public abstract void Delete(IEnumerable<TEntity> entities, string auditnote);

        //public abstract void Delete(TEntity entity, string auditnote, Action<TEntity, Exception> callback);
        //public abstract void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception> callback);

        //public abstract void Delete(object entity, string auditnote);
        //public abstract void Delete(IEnumerable<object> entities, string auditnote);

        public DataTable LoadDataTable(Columns<TEntity> columns, object[][] data)
        {
            var result = new DataTable(typeof(TEntity).EntityName());

            var cols = CoreUtils.GetColumns(columns);
            foreach (var col in cols.Items)
                result.Columns.Add(col.Property, col.Expression.Type);

            result.BeginLoadData();
            foreach (var row in data.AsEnumerable())
                result.LoadDataRow(row, true);
            result.EndLoadData();

            return result;
        }

        //public abstract IEnumerable<object[]> List(Filter<TEntity> filter = null, Columns<TEntity> columns = null, SortOrder<TEntity> sort = null);
        //public abstract void List(Filter<TEntity> filter, Columns<TEntity> columns, SortOrder<TEntity> sort, Action<IEnumerable<object[]>, Exception> callback);
        //public abstract IEnumerable<object[]> List(object filter = null, object columns = null, object sort = null);

        //public abstract TEntity[] Load(Filter<TEntity> filter = null, SortOrder<TEntity> sort = null);
        //public abstract void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, Action<TEntity[], Exception> callback);
        //public abstract Entity[] Load(object filter = null, object sort = null);

        //public abstract CoreTable Query(Filter<TEntity> filter = null, Columns<TEntity> columns = null, SortOrder<TEntity> sort = null);
        //public abstract void Query(Filter<TEntity> filter, Columns<TEntity> columns, SortOrder<TEntity> sort, Action<CoreTable, Exception> callback);
        //public abstract CoreTable Query(object filter = null, object columns = null, object sort = null);

        //public abstract void Save(TEntity entity, string auditnote);
        //public abstract void Save(IEnumerable<TEntity> entities, string auditnote);

        //public abstract void Save(TEntity entity, string auditnote, Action<TEntity, Exception> callback);
        //public abstract void Save(IEnumerable<TEntity> entity, string auditnote, Action<IEnumerable<TEntity>, Exception> callback);

        //public abstract void Save(object entity, string auditnote);
        //public abstract void Save(IEnumerable<object> entities, string auditnote);

        #region Validation

        public virtual ValidationData Validate(string userid, string password, Guid session)
        {
            return DoValidate(userid, password, session);
        }
        protected abstract ValidationData DoValidate(string userid, string password, Guid session = default);

        public virtual ValidationData Validate(string pin, Guid session)
        {
            return DoValidate(pin, session);
        }
        protected abstract ValidationData DoValidate(string pin, Guid session = default);
        
        public virtual ValidationData Validate(Guid session)
        {
            return DoValidate(session);
        }
        protected abstract ValidationData DoValidate(Guid session = default);

        #endregion

        #region Query

        public CoreTable Query(object? filter = null, object? columns = null, object? sort = null)
        {
            return DoQuery((Filter<TEntity>?)filter, (Columns<TEntity>?)columns, (SortOrder<TEntity>?)sort);
        }

        public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? sort = null)
        {
            return DoQuery(filter, columns, sort);
        }

        public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, Action<CoreTable?, Exception?> callback)
        {
            Task.Run(() =>
            {
                Exception? err = null;
                CoreTable? result = null;
                try
                {
                    result = DoQuery(filter, columns, sort);
                }
                catch (Exception e)
                {
                    err = e;
                }
                finally
                {
                    callback.Invoke(result, err);
                }
            });
        }

        protected abstract CoreTable DoQuery(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort = null);

        #endregion

        #region Load

        public Entity[] Load(object? filter = null, object? sort = null)
        {
            return DoLoad((Filter<TEntity>?)filter, (SortOrder<TEntity>?)sort);
        }

        public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null)
        {
            return DoLoad(filter, sort);
        }

        public void Load(Filter<TEntity>? filter, SortOrder<TEntity>? sort, Action<TEntity[]?, Exception?> callback)
        {
            Task.Run(() =>
            {
                Exception? err = null;
                TEntity[]? result = null;
                try
                {
                    result = DoLoad(filter, sort);
                }
                catch (Exception e)
                {
                    err = e;
                }
                finally
                {
                    callback.Invoke(result, err);
                }
            });
        }

        protected abstract TEntity[] DoLoad(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null);

        #endregion

        #region Save

        public void Save(object entity, string auditnote)
        {
            var e = (TEntity)entity;
            DoSave(e, auditnote);
        }

        public void Save(IEnumerable<object> entities, string auditnote)
        {
            var items = entities.Select(x => (TEntity)x);
            DoSave(items, auditnote);
        }

        public void Save(TEntity entity, string auditnote)
        {
            DoSave(entity, auditnote);
        }

        public void Save(IEnumerable<TEntity> entities, string auditnote)
        {
            DoSave(entities, auditnote);
        }

        public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
        {
            Task.Run(() =>
            {
                Exception? err = null;
                try
                {
                    DoSave(entity, auditnote);
                }
                catch (Exception e)
                {
                    err = e;
                }
                finally
                {
                    callback.Invoke(entity, err);
                }
            });
        }

        public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
        {
            Task.Run(() =>
            {
                Exception? err = null;
                try
                {
                    var items = entities.ToArray();
                    DoSave(entities, auditnote);
                }
                catch (Exception e)
                {
                    err = e;
                }
                finally
                {
                    callback.Invoke(entities, err);
                }
            });
        }
        
        protected abstract void DoSave(TEntity entity, string auditnote);

        protected abstract void DoSave(IEnumerable<TEntity> entities, string auditnote);

        #endregion

        #region Delete

        public void Delete(object entity, string auditnote)
        {
            DoDelete((TEntity)entity, auditnote);
        }

        public void Delete(IList<object> entities, string auditnote)
        {
            var items = entities.Select(x => (TEntity)x).ToList();
            DoDelete(items, auditnote);
        }

        public void Delete(TEntity entity, string auditnote)
        {
            DoDelete(entity, auditnote);
        }

        public void Delete(IList<TEntity> entities, string auditnote)
        {
            DoDelete(entities, auditnote);
        }

        public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
        {
            Task.Run(() =>
                {
                    Exception? err = null;
                    try
                    {
                        DoDelete(entity, auditnote);
                    }
                    catch (Exception e)
                    {
                        err = e;
                    }
                    finally
                    {
                        callback.Invoke(entity, err);
                    }
                }
            );
        }

        public void Delete(IList<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
        {
            Task.Run(() =>
            {
                Exception? err = null;
                var items = entities;
                try
                {
                    DoDelete(entities, auditnote);
                }
                catch (Exception e)
                {
                    err = e;
                }
                finally
                {
                    callback.Invoke(entities, err);
                }
            });
        }

        protected abstract void DoDelete(TEntity entity, string auditnote);

        protected abstract void DoDelete(IList<TEntity> entities, string auditnote);

        #endregion

        #region MultipleTables

        public Dictionary<string, CoreTable> QueryMultiple(Dictionary<string, IQueryDef> queries)
        {
            return DoQueryMultiple(queries);
        }

        protected abstract Dictionary<string, CoreTable> DoQueryMultiple(Dictionary<string, IQueryDef> queries);

        #endregion

        #region 2FA

        public bool Check2FA(string code, Guid? session)
        {
            return DoCheck2FA(code, session);
        }
        protected abstract bool DoCheck2FA(string code, Guid? session);


        #endregion

        #region Ping

        public bool Ping()
        {
            return DoPing();
        }

        protected abstract bool DoPing();

        #endregion
        
        #region Info
        
        public abstract DatabaseInfo Info();
        
        #endregion
        
    }
}