using STSdb4.Database;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DeviceRepairAndOptimization.Data
{
    public class STSdbMaintenance
    {
        public List<T> GetDatas<T>(string dbFile, string tableName) where T : class
        {
            List<T> lst = null;
            using (IStorageEngine db = STSdb.FromFile(dbFile))
            {
                ITable<int, T> dbDatas = db.OpenXTable<int, T>(tableName);
                if (dbDatas != null && dbDatas.Count() > 0)
                {
                    lst = dbDatas.Select(x => x.Value).ToList<T>();
                }
            }
            return lst;
        }

        public bool InsertDatas<T>(string dbFile, string tableName, Dictionary<int, T> lst) where T : class
        {
            bool result = false;

            if (lst != null && lst.Count > 0)
            {
                using (IStorageEngine db = STSdb.FromFile(dbFile))
                {
                    try
                    {
                        ITable<int, T> Datas = db.OpenXTable<int, T>(tableName);

                        long Key = 0;
                        foreach (KeyValuePair<int, T> item in lst)
                        {
                            if (item.Key == 0)
                            {
                                if (Key == 0)
                                    Key = Datas.Count();
                                Datas[(int)Key] = item.Value;
                                Key++;
                            }
                            else if (Datas.Any(x => x.Key == item.Key))
                            {
                                Datas.Replace(item.Key, item.Value);
                            }
                            else
                            {
                                Datas[item.Key] = item.Value;
                            }
                        }

                        db.Commit();
                        result = true;
                    }
                    catch (System.Exception ex)
                    {
                        throw new System.Exception(ex.Message);
                    }
                }
            }

            return result;
        }

        public bool DeleteData<T>(string dbFile, string tableName, int key) where T : class
        {
            using (IStorageEngine db = STSdb.FromFile(dbFile))
            {
                ITable<int, T> data = db.OpenXTable<int, T>(tableName);
                if (data != null)
                {
                    data.Delete(key);
                    db.Commit();
                    return true;
                }
            }
            return false;
        }
    }
}
