using EasyDevCore.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyDev.Database.EntityTable
{
    /// <summary>
    /// 
    /// </summary>
    public static class DataRowExtensions
    {
        /// <summary>
        /// Gets a value indicating whether this instance is new.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is new; otherwise, <c>false</c>.
        /// </value>
        public static bool IsNew(this DataRow row) => row.RowState == DataRowState.Added;

        /// <summary>
        /// Gets a value indicating whether this instance is deleted.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is new; otherwise, <c>false</c>.
        /// </value>
        public static bool IsDeleted(this DataRow row) => row.RowState == DataRowState.Deleted;

        /// <summary>
        /// Gets a value indicating whether this instance is changed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is changed; otherwise, <c>false</c>.
        /// </value>
        public static bool IsChanged(this DataRow row) => row.RowState == DataRowState.Added || row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Modified;

        /// <summary>
        /// Determines whether the specified column index is changed.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <returns>
        ///   <c>true</c> if the specified column index is changed; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsChanged(this DataRow row, int columnIndex)
        {
            var curValue = row.HasVersion(DataRowVersion.Current) ? row[columnIndex, DataRowVersion.Current] : null;
            var oldValue = row.HasVersion(DataRowVersion.Original) ? row[columnIndex, DataRowVersion.Original] : null;
            if (oldValue != null && curValue == null || oldValue == null && curValue != null
                || oldValue != curValue)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Determines whether the specified column name is changed.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <returns>
        ///   <c>true</c> if the specified column name is changed; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsChanged(this DataRow row, string columnName)
        {
            var curValue = row.HasVersion(DataRowVersion.Current) ? row[columnName, DataRowVersion.Current] : null;
            var oldValue = row.HasVersion(DataRowVersion.Original) ? row[columnName, DataRowVersion.Original] : null;
            if (oldValue != null && curValue == null || oldValue == null && curValue != null
                || oldValue != curValue)
            {
                return true;
            }
            return false;
        }

        /// <summary>Gets the value, if value = DBNull.Value, return null value</summary>
        /// <param name="row"></param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <returns>
        /// </returns>
        public static object GetValue(this DataRow row, int columnIndex) => row[columnIndex] == DBNull.Value ? null : row[columnIndex];

        /// <summary>
        /// Gets the value, if value = DBNull.Value, return null value
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <returns></returns>
        public static object GetValue(this DataRow row, string columnName) => row[columnName] == DBNull.Value ? null : row[columnName];

        /// <summary>
        /// Gets the value, if value = DBNull.Value, return valueIfNull value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row">The row.</param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <param name="valueIfNull">The value if null.</param>
        /// <returns></returns>
        public static T GetValue<T>(this DataRow row, int columnIndex, T valueIfNull = default) => row[columnIndex] == DBNull.Value ? valueIfNull : (T)row[columnIndex];

        /// <summary>
        /// Gets the value, if value = DBNull.Value, return valueIfNull value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row">The row.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="valueIfNull">The value if null.</param>
        /// <returns></returns>
        public static T GetValue<T>(this DataRow row, string columnName, T valueIfNull = default) => row[columnName] == DBNull.Value ? valueIfNull : (T)row[columnName];

        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static bool SetValue(this DataRow row, int columnIndex, object value)
        {
            object oldValue = row[columnIndex];
            bool newValueIsNull = value == null || value.Equals(DBNull.Value);
            bool oldValueIsNull = oldValue == DBNull.Value;
            if (!newValueIsNull || !oldValueIsNull)
            {
                if (newValueIsNull)
                {
                    row[columnIndex] = DBNull.Value;
                    return true;
                }
                if (oldValueIsNull || !value.Equals(oldValue))
                {
                    row[columnIndex] = value;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static bool SetValue(this DataRow row, string columnName, object value) => row.SetValue(row.Table.Columns[columnName].Ordinal, value);

        /// <summary>
        /// Deletes the specified source.
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static int Delete<TSource>(this IEnumerable<TSource> source)
            where TSource : DataRow
        {
            int rowsEffected = 0;
            foreach (var row in source)
            {
                row.Delete();
                rowsEffected++;
            }
            return rowsEffected;
        }

        /// <summary>
        /// Updates the DataRow.
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        /// <exception cref="Exception">string.Format("Invalid column name [{0}]", kp.Key)</exception>
        public static TSource Update<TSource>(this TSource source, params object[] values)
            where TSource : DataRow
        {
            var args = ArgumentHelper.GetArgValues(values);
            var table = source.Table;
            foreach (var kp in args)
            {
                int colIndex = table.Columns.IndexOf(kp.Key);
                if (colIndex >= 0)
                {
                    source.SetValue(colIndex, kp.Value);
                }
                else
                {
                    throw new Exception(string.Format("Invalid column name [{0}]", kp.Key));
                }
            }
            return source;
        }

        /// <summary>
        /// Updates this instance with the values of the data row
        /// </summary>
        /// <param name="row">The data row.</param>
        /// <param name="source">The source.</param>
        /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
        /// <param name="exceptColumnNames">The except column names (splits by comma).</param>
        /// <returns></returns>
        public static DataRow UpdateFrom(this DataRow row, DataRow source, string columnNames = "", string exceptColumnNames = "")
        {
            IDictionary<string, string> listColumns = row.Table.GetMatchedColumnsList(source.Table, columnNames, exceptColumnNames);
            foreach (var map in listColumns)
            {
                row[map.Key] = source[map.Value];
            }
            return row;
        }

        /// <summary>
        /// Updates this row with the values of the row view
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="source">The row view.</param>
        /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
        /// <param name="exceptColumnNames">The except column names (splits by comma).</param>
        /// <returns></returns>
        public static DataRow UpdateFrom(this DataRow row, DataRowView source, string columnNames = "", string exceptColumnNames = "")
        {
            IDictionary<string, string> listColumns = row.Table.GetMatchedColumnsList(source.Row.Table, columnNames, exceptColumnNames);
            foreach (var map in listColumns)
            {
                row[map.Key] = source[map.Value];
            }
            return row;
        }

        /// <summary>
        /// Updates to model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="model">The model.</param>
        /// <param name="listProperties">The list properties.</param>
        /// <param name="modelStatusField">The model status field.</param>
        internal static void UpdateToModel<T>(this DataRow source, T model, IDictionary<string, PropertyDescriptor> listProperties, string modelStatusField = "")
        {
            string propName = string.Empty;
            try
            {
                foreach (var prop in listProperties)
                {
                    PropertyDescriptor p = prop.Value;
                    p.SetValue(model, source[prop.Key]);
                }
            }
            catch (Exception ex)
            {
                ex.Data["PropertyName"] = propName;
                throw;
            }
            if (!string.IsNullOrWhiteSpace(modelStatusField)) model.SetPropertyValue(modelStatusField, source.RowState);
        }

        /// <summary>
        /// Converts to model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="listProperties">The list properties.</param>
        /// <param name="modelStatusField">The model status field has receive status of source (field type must be DataRowState).</param>
        /// <param name="method">The method.</param>
        /// <returns></returns>
        internal static T ConvertToModel<T>(this DataRow source, IDictionary<string, PropertyDescriptor> listProperties, string modelStatusField = "", Action<T> method = null)
        {
            T item = default;
            item = Activator.CreateInstance<T>();
            source.UpdateToModel(item, listProperties, modelStatusField);
            if (method != null) method(item);
            return item;
        }

        /// <summary>
        /// Convert to Model DataRow.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
        /// <param name="exceptColumnNames">The except column names.</param>
        /// <param name="modelStatusField">The model status field has receive status of source (field type must be DataRowState).</param>
        /// <param name="ignorePrefix">The ignore prefix for ignore prefix characters when mapping field name with column name.</param>
        /// <param name="method">The method.</param>
        /// <returns>T.</returns>
        public static T ConvertToModel<T>(this DataRow source, string columnNames = "", string exceptColumnNames = "", string modelStatusField = "", string ignorePrefix = "", Action<T> method = null)
        {
            Type DataRowType = typeof(T);
            IDictionary<string, PropertyDescriptor> properties = (source.Table as DataTable).GetMatchedPropertiesList<T>(columnNames, exceptColumnNames, ignorePrefix);
            T item = source.ConvertToModel<T>(properties, modelStatusField);
            if (method != null) method(item);
            return item;
        }

        /// <summary>
        /// Updates from model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="item">The item.</param>
        /// <param name="listProperties">The list properties.</param>
        internal static void UpdateFromModel<T>(this DataRow source, T item, IDictionary<string, PropertyDescriptor> listProperties)
        {
            string propName = string.Empty;
            try
            {
                foreach (var prop in listProperties)
                {
                    PropertyDescriptor p = prop.Value;
                    propName = prop.Key;
                    source[propName] = p.GetValue(item);
                }
            }
            catch (Exception ex)
            {
                ex.Data["PropertyName"] = propName;
                throw;
            }
        }

        /// <summary>
        /// Updates from Model DataRow.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="item">The item.</param>
        /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
        /// <param name="exceptColumnNames">The except column names.</param>
        public static void UpdateFromModel<T>(this DataRow source, T item, string columnNames = "", string exceptColumnNames = "")
        {
            IDictionary<string, PropertyDescriptor> properties = (source.Table as DataTable).GetMatchedPropertiesList<T>(columnNames, exceptColumnNames);
            source.UpdateFromModel(item, properties);
        }

        /// <summary>
        /// Updates to model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="model">The model.</param>
        /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
        /// <param name="exceptColumnNames">The except column names.</param>
        /// <param name="modelStatusField">The model status field.</param>
        public static void UpdateToModel<T>(this DataRow source, T model, string columnNames = "", string exceptColumnNames = "", string modelStatusField = "")
        {
            IDictionary<string, PropertyDescriptor> properties = (source.Table as DataTable).GetMatchedPropertiesList<T>(columnNames, exceptColumnNames);
            source.UpdateToModel(model, properties, modelStatusField);
        }
    }
}
