using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace InABox.Core
{
    [Serializable]
    public class CoreRow : ICoreRow
    {
        #region Fields

        [NonSerialized]
        private static Dictionary<int, string> _accessedcolumns = new Dictionary<int, string>();

        [NonSerialized]
        private Dictionary<string, int> _columnindexes = new Dictionary<string, int>();

        #endregion

        #region Properties

        [DoNotSerialize]
        [field: NonSerialized]
        public CoreTable Table { get; private set; }
        public List<object?> Values { get; private set; }

        [DoNotSerialize]
        public int Index => Table.Rows.IndexOf(this);

        #endregion

        protected internal CoreRow(CoreTable owner)
        {
            Table = owner;
            Values = new List<object?>();
        }

        public static CoreRow[] None
        {
            get { return new CoreRow[] { }; }
        }

        //private DynamicObject rowObject;

        public Dictionary<string, object?> ToDictionary(string[] exclude)
        {
            var result = new Dictionary<string, object?>();
            foreach (var column in Table.Columns.Where(x => !exclude.Contains(x.ColumnName)))
                result[column.ColumnName] = this[column.ColumnName];
            return result;
        }

        [DoNotSerialize]
        public object? this[string columnName]
        {
            get =>
                //return this.RowObject.GetValue<object>(columnName);
                Get<object>(columnName);
            set =>
                //this.RowObject.SetValue(columnName, value);
                Set(columnName, value);
        }

        public BaseObject ToObject(Type t)
        {
            var entity = (Activator.CreateInstance(t) as BaseObject)!;
            entity.SetObserving(false);

            if (!Table.Setters.TryGetValue("", out var setters))
            {
                setters = new List<Action<object, object>?>();
                Table.Setters[""] = setters;
            }
            
            var bFirst = !setters.Any();

            for (var i = 0; i < Table.Columns.Count; i++)
            {
                var column = Table.Columns[i].ColumnName;
                var value = this[column];
                try
                {
                    if (bFirst)
                    {
                        var prop = DatabaseSchema.Property(t, column);
                        setters.Add(prop?.Setter());
                    }

                    var setter = setters[i];
                    if (setter != null && value != null)
                        setter.Invoke(entity, value);
                    else
                        CoreUtils.SetPropertyValue(entity, column, value);
                }
                catch (Exception e)
                {
                    Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
                }
            }

            entity.CommitChanges();
            entity.SetObserving(true);
            return entity;
        }

        public T ToObject<T>() where T : BaseObject, new()
        {
            return (ToObject(typeof(T)) as T)!;
        }

        public T Get<T>(int col, bool usedefault = true)
        {
            if (col < 0 || col >= Values.Count)
            {
                if (usedefault)
                    return CoreUtils.GetDefault<T>();
                throw new Exception(string.Format("Column [{0}] does not exist!", col));
            }

            return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();

        }
        
        public T Get<T>(string columnname, bool usedefault = true)
        {
            var col = GetColumn(columnname);

            if (col < 0 || col >= Values.Count)
            {
                if (usedefault)
                    return CoreUtils.GetDefault<T>();
                throw new Exception(string.Format("Column [{0}] does not exist!", columnname));
            }

            return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
        }

        public TType Get<TSource, TType>(Expression<Func<TSource, TType>> expression, bool usedefault = true)
        {
            var colname = GetColName(expression);
            //String colname = CoreUtils.GetFullPropertyName(expression, ".");
            return Get<TType>(colname, usedefault);
        }

        public void Set<TSource, TType>(Expression<Func<TSource, TType>> expression, TType value)
        {
            var colname = GetColName(expression);
            //String colname = CoreUtils.GetFullPropertyName(expression, ".");
            Set(colname, value);
        }

        public void Set<T>(int col, T value)
        {
            while (Values.Count <= col)
                Values.Add(Table.Columns[Values.Count].DataType.GetDefault());

            Values[col] = value;
        }
        
        public void Set<T>(string columnname, T value)
        {
            var col = GetColumn(columnname);
            if (col < 0)
                throw new Exception("Column not found: " + columnname);

            while (Values.Count <= col)
                Values.Add(Table.Columns[Values.Count].DataType.GetDefault());

            Values[col] = value;

            //this.RowObject.SetValue(columnname, value);
        }

        public void LoadValues(IEnumerable<object?> values)
        {
            Values = values.ToList();
        }

        public T ToObject<TSource, TLink, T>(Expression<Func<TSource, TLink>> property)
            where TLink : IEntityLink<T>
            where T : BaseObject, new()
        {
            var entity = new T();
            entity.SetObserving(false);

            var prefix = CoreUtils.GetFullPropertyName(property, ".");
            if (!Table.Setters.TryGetValue(prefix, out var setters))
            {
                setters = new List<Action<object, object>?>();
                Table.Setters[prefix] = setters;
            }
            var bFirst = !setters.Any();

            var cols = Table.Columns.Where(x => x.ColumnName.StartsWith(prefix + ".")).ToArray();

            for (var i = 0; i < cols.Length; i++)
            {
                var column = cols[i].ColumnName;

                var prop = column.Substring((prefix + ".").Length);
                var value = this[column];
                try
                {
                    if (bFirst)
                    {
                        var p2 = DatabaseSchema.Property(typeof(T), prop);
                        setters.Add(p2?.Setter());
                    }

                    var setter = setters[i];
                    if (setter != null && value != null)
                        setter.Invoke(entity, value);
                    else
                        CoreUtils.SetPropertyValue(entity, prop, value);
                }
                catch (Exception e)
                {
                    Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
                }
            }

            entity.CommitChanges();
            entity.SetObserving(true);
            return entity;
        }

        private string GetColName<TSource, TType>(Expression<Func<TSource, TType>> expression)
        {
            //int hash = expression.GetHashCode();
            //if (_accessedcolumns.ContainsKey(hash))
            //    return _accessedcolumns[hash];
            var colname = CoreUtils.GetFullPropertyName(expression, ".");
            //_accessedcolumns[hash] = colname;
            return colname;
        }

        private int GetColumn(string columnname)
        {
            if (_columnindexes.ContainsKey(columnname))
                return _columnindexes[columnname];

            for (var i = 0; i < Table.Columns.Count; i++)
                if (Table.Columns[i].ColumnName.Equals(columnname))
                {
                    _columnindexes[columnname] = i;
                    return i;
                }

            _columnindexes[columnname] = -1;
            return -1;
        }

    }
}