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

namespace InABox.Core
{
    [Serializable]
    public class CoreRow : ICoreRow, IEnumerable<KeyValuePair<string, object?>>
    {
        #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?>(owner.Columns.Count);
        }

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

        //private DynamicObject rowObject;

        public Dictionary<string, object?> ToDictionary(string[]? exclude = null)
        {
            var result = new Dictionary<string, object?>();
            
            var columns = exclude == null
                ? Table.Columns
                : Table.Columns.Where(x => !exclude.Contains(x.ColumnName));
            
            foreach (var column in columns)
                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);
        }

        /// <summary>
        /// Fill an object with the data from this row.
        /// </summary>
        /// <remarks>
        /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
        /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
        /// </remarks>
        /// <param name="t">The type of <paramref name="obj"/>.</param>
        /// <param name="obj">The object to fill.</param>
        /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
        public void FillObject(Type t, BaseObject obj, bool overrideExisting = false)
        {
            obj.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 =  i < Values.Count
                    ? Values[i]
                    : CoreUtils.GetDefault(Table.Columns[i].DataType);
                try
                {
                    if (obj.LoadedColumns.Add(column) || overrideExisting)
                    {
                        if (bFirst)
                        {
                            var prop = DatabaseSchema.Property(t, column);
                            setters.Add(prop?.Setter());
                        }

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

            obj.SetObserving(true);
        }

        /// <summary>
        /// Fill an object with the data from this row.
        /// </summary>
        /// <remarks>
        /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
        /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
        /// </remarks>
        /// <param name="obj">The object to fill.</param>
        /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
        public void FillObject<T>(T obj, bool overrideExisting = false) where T : BaseObject
        {
            FillObject(typeof(T), obj, overrideExisting: overrideExisting);
        }

        public BaseObject ToObject(Type t)
        {
            var entity = (Activator.CreateInstance(t) as BaseObject)!;
            FillObject(t, entity, overrideExisting: 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 Update<TSource, TType>(Expression<Func<TSource, TType>> expression, Func<TType, TType> update)
        {
            var colname = GetColName(expression);
            //String colname = CoreUtils.GetFullPropertyName(expression, ".");
            Set(colname, update(Get<TType>(colname)));
        }

        public void Set<T>(int col, T value)
        {
            if(Values.Count <= col)
            {
                while (Values.Count < col)
                    Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
                Values.Add(value);
            }
            else
            {
                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);

            if(Values.Count <= col)
            {
                while (Values.Count < col)
                    Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
                Values.Add(value);
            }
            else
            {
                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.TryGetValue(columnname, out var index))
                return index;

            index = Table.GetColumnIndex(columnname);
            _columnindexes[columnname] = index;
            return index;
        }

        #region IEnumerable

        public IEnumerable<KeyValuePair<string, object?>> Entries
        {
            get
            {
                var columns = Table.Columns;
                for (var i = 0; i < columns.Count; i++)
                {
                    var column = columns[i];
                    var value =  i < Values.Count
                        ? Values[i]
                        : CoreUtils.GetDefault(column.DataType);
                    yield return new KeyValuePair<string, object?>(column.ColumnName, value);
                }
            }
        }

        public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() => Entries.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => Entries.GetEnumerator();

        #endregion
    }

    public static class CoreRowExtensions
    {
        public static IEnumerable<T> ToObjects<T>(this IEnumerable<CoreRow> rows)
            where T : BaseObject, new()
        {
            return rows.Select(x => x.ToObject<T>());
        }

        public static List<T> ToList<T>(this IList<CoreRow> rows)
            where T : BaseObject, new()
        {
            var result = new List<T>(rows.Count);
            for (var i = 0; i < rows.Count; ++i)
            {
                result.Add(rows[i].ToObject<T>());
            }
            return result;
        }

        public static T[] ToArray<T>(this IList<CoreRow> rows)
            where T : BaseObject, new()
        {
            var result = new T[rows.Count];
            for (var i = 0; i < rows.Count; ++i)
            {
                result[i] = rows[i].ToObject<T>();
            }
            return result;
        }
    }
}