using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InABox.Clients;

namespace InABox.Core
{
    public class DigitalFormDataModel<TEntity, TEntityLink, TInstance> : IDigitalFormDataModel
        where TEntity : Entity, IRemotable, IPersistent, new()
        where TEntityLink : EntityLink<TEntity>
        where TInstance : Entity, IRemotable, IPersistent, IDigitalFormInstance<TEntityLink>, new()
    {
        private readonly bool bRequiresLoad = true;
        public DigitalFormDataModel(Guid entityid, Guid instanceid, DigitalFormVariable[] variables)
        {
            Entity = new TEntity();
            Entity.ID = entityid;
            Entity.CommitChanges();
            Instance = new TInstance();
            Instance.ID = instanceid;
            Instance.CommitChanges();
            Variables = variables;
            bRequiresLoad = true;
        }

        public DigitalFormDataModel(TEntity entity, TInstance instance, DigitalFormVariable[] variables)
        {
            Entity = entity;
            Instance = instance;
            Variables = variables;
            bRequiresLoad = false;
        }

        public Entity Entity { get; set; }

        public object? GetEntityValue(string name)
        {
            try
            {
                return CoreUtils.GetPropertyValue(Entity, name);
            }
            catch
            {
                return null;
            }
        }

        public void SetEntityValue(string name, object? value)
        {
            try
            {
                CoreUtils.SetPropertyValue(Entity, name, value);
            }
            catch (Exception e)
            {
                Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
            }
        }

        IDigitalFormInstance IDigitalFormDataModel.Instance
        {
            get => Instance;
            set
            {
                Instance = (TInstance)value;
            }
        }

        public TInstance Instance { get; set; }
        
        public DigitalFormVariable[] Variables { get; set; }

        public event DigitalFormUpdateHandler OnModelSaved;

        public event DigitalFormBeforeUpdateHandler BeforeModelSaved;

        public void Load(Action<IDigitalFormDataModel>? callback = null)
        {
            if (!bRequiresLoad)
            {
                callback?.Invoke(this);
                return;
            }

            var client = new MultiQuery();

            DoAddQueries(client);

            if (callback == null)
            {
                if (client.Count > 0)
                {
                    client.Query();
                    DoParseQueries(client);
                }
            }
            else
            {
                if (client.Count > 0)
                    client.Query(c =>
                    {
                        DoParseQueries(client);
                        callback.Invoke(this);
                    });
                else
                    callback.Invoke(this);
            }
        }

        public void Update(Action<IDigitalFormDataModel>? callback = null)
        {
            //this never get used and causes a crash in the app for Job ITP forms - maybe time for a rebuild?
            //if (!bRequiresLoad)
            //{
            //    callback.Invoke(this);
            //    return;
            //}

            if (callback == null)
                DoUpdate();
            else
                Task.Run(() =>
                {
                    DoUpdate();
                    callback.Invoke(this);
                });
        }

        public virtual void AddQueries(MultiQuery client)
        {
        }


        private void DoAddQueries(MultiQuery client)
        {
            if (Entity.ID != Guid.Empty)
            {
                client.Add(
                    new QueryDef<TEntity>(
                        new Filter<TEntity>(x => x.ID).IsEqualTo(Entity.ID),
                        DFUtils.EntityColumns<TEntity>(Variables),
                        null
                    ),
                    typeof(TEntity)
                );
            }

            if (Instance.ID != Guid.Empty)
                client.Add(
                    new QueryDef<TInstance>(
                        new Filter<TInstance>(x => x.ID).IsEqualTo(Instance.ID),
                        Columns.None<TInstance>().Add
                        (
                            x => x.ID, 
                            x => x.Number,
                            x => x.FormData, 
                            x => x.Form.ID,
                            x => x.Form.Description,
                            x => x.Form.DescriptionExpression,
                            x => x.FormCompleted,
                            x => x.FormCompletedBy.ID,
                            x => x.Created,
                            x => x.FormOpen,
                            x => x.BlobData
                            
                            ),
                        null
                    ),
                    typeof(TInstance)
                );

            AddQueries(client);
        }

        public virtual void ParseQueries(MultiQuery client)
        {
        }

        private void DoParseQueries(MultiQuery client)
        {
            if (client.Contains(typeof(TEntity)))
            {
                var table = client.Get(typeof(TEntity));
                if (table.Rows.Any())
                    Entity = table.Rows.First().ToObject<TEntity>();
            }

            if (client.Contains(typeof(TInstance)))
            {
                var table = client.Get(typeof(TInstance));
                if (table.Rows.Any())
                    Instance = table.Rows.First().ToObject<TInstance>();
            }

            ParseQueries(client);
        }

        protected virtual void AddPrimaryUpdates(MultiSave client)
        {
        }

        protected virtual void AddSecondaryUpdates(MultiSave client)
        {
        }

        public void DuplicateInstance()
        {
            var formid = Instance.Form.ID;
            Instance = new TInstance();
            Instance.Parent.ID = Entity.ID;
            Instance.Form.ID = formid;
        }

        private void DoUpdate()
        {
            var result = DigitalFormDataModel.EvaluateExpression(Instance.Form.DescriptionExpression, Instance, Entity);
            Instance.Description = !String.IsNullOrWhiteSpace(result) 
                ? result 
                : Instance.Form.Description;
            
            BeforeModelSaved?.Invoke(this);

            var entityaudittrail = "";
            var instanceaudittrail = "";

            var parents = new MultiSave();
            if (Entity.IsChanged())
            {
                parents.Add(typeof(TEntity), Entity);
                entityaudittrail = "Updated from App - Digital Forms Module";
            }
            else if (Entity.ID == Guid.Empty)
            {
                parents.Add(typeof(TEntity), Entity);
                entityaudittrail = "Created from App - Digital Forms Module";
            }

            AddPrimaryUpdates(parents);

            parents.Save(null, entityaudittrail);

            ((IDigitalFormInstance<TEntityLink>)Instance).Parent.ID = Entity.ID; //be careful of bug here in future due to cast            

            var children = new MultiSave();
            if (Instance.IsChanged())
            {
                children.Add(typeof(TInstance), (TInstance)Instance);
                instanceaudittrail = "Updated from App - Digital Forms Module";
            }
            else if (Entity.ID == Guid.Empty)
            {
                children.Add(typeof(TInstance), (TInstance)Instance);
                instanceaudittrail = "Created from App - Digital Forms Module";
            }

            AddSecondaryUpdates(children);

            children.Save(null, instanceaudittrail);

            OnModelSaved?.Invoke(this);
        }
    }
    public static class DigitalFormDataModel
    {
        public static string? EvaluateExpression(string expression, IDigitalFormInstance instance, Entity entity)
        {
            if (string.IsNullOrWhiteSpace(expression))
                return null;
            
            Dictionary<string, object?> variables = new Dictionary<string, object?>();
                
            var formData = DigitalForm.DeserializeFormData(instance);
            if(formData != null)
            {
                foreach (var item in formData.Items())
                    variables[$"Data.{item.Key}"] = item.Value;
            }
                
            foreach (var property in DatabaseSchema.Properties(instance.GetType()).Where(x => !x.Name.StartsWith("Parent.")))
                variables[$"Form.{property.Name}"] = property.Getter()(instance);
                
            foreach (var property in DatabaseSchema.Properties(entity.GetType()))
                variables[$"{entity.GetType().Name}.{property.Name}"] = property.Getter()(entity);

            var exp = new CoreExpression(expression);
            return exp.Evaluate(variables)?.ToString();
        }

        public static void Update(IDigitalFormInstance instance, Entity entity)
        {
            var result = EvaluateExpression(instance.Form.DescriptionExpression, instance, entity);
            instance.Description = !String.IsNullOrWhiteSpace(result) 
                ? result 
                : instance.Form.Description;

            var entityaudittrail = "";
            var instanceaudittrail = "";

            var parents = new MultiSave();
            if (entity.IsChanged())
            {
                parents.Add(entity);
                entityaudittrail = "Updated from App - Digital Forms Module";
            }
            else if (entity.ID == Guid.Empty)
            {
                parents.Add(entity);
                entityaudittrail = "Created from App - Digital Forms Module";
            }

            parents.Save(null, entityaudittrail);

            instance.Parent.ID = entity.ID;

            var children = new MultiSave();
            if (instance.IsChanged())
            {
                children.Add((Entity)instance);
                instanceaudittrail = "Updated from App - Digital Forms Module";
            }
            else if (entity.ID == Guid.Empty)
            {
                children.Add((Entity)instance);
                instanceaudittrail = "Created from App - Digital Forms Module";
            }
            children.Save(null, instanceaudittrail);
            
            DFUtils.OnSave(instance.GetType(), instance, entity);
        }
    }
}