using CloudBuilder.Core.Utility;
using Krypton.Toolkit;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Gui
{
    public class ExDataGridViewSnapshot
    {
        public DataTable DataTableSource;

        public DataTable DeleteDataTableSource;

        public List<dynamic> DataSource;

        public ExDataGridViewSnapshot()
        {

        }

        public T[] GetAddRows<T>() where T : new()
        {
            return GetRows<T>(DataRowState.Added);
        }


        public T[] GetDeleteRows<T>() where T : new()
        {
            if (DeleteDataTableSource.Rows.Count == 0) return null;

            List<T> l = DataTableConvertor.ConvertToList<T>(DeleteDataTableSource);

            return l.ToArray();
        }

        public T[] GetUpdateRows<T>() where T : new()
        {
            return GetRows<T>(DataRowState.Modified);
        }


        private T[] GetRows<T>(DataRowState drs) where T : new()
        {
            if (DataTableSource == null || DataTableSource.Rows.Count == 0) return null;

            DataTable dt = DataTableSource.Clone();
            foreach (DataRowView drv in DataTableSource.DefaultView)
            {
                if (drv.Row.RowState != drs || drv.Row.RowState == DataRowState.Deleted) continue;

                //drv.Row.AcceptChanges();
                dt.ImportRow(drv.Row);
            }

            if (dt.Rows.Count == 0) return null;

            List<T> l = DataTableConvertor.ConvertToList<T>(dt);

            return l.ToArray();
        }

        public List<T> GetAllRows<T>() where T : new()
        {
            return DataTableConvertor.ConvertToList<T>(DataTableSource);
        }
    }
}
