using AutoMapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.Blowing.DbViewer.Core
{
    public class DbViewerModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;


        public string DbDirPath { get; set; } = @"D:\blowingdata";

        public DbProfilePack Pack { get; set; }
        public bool IsPackReady { get; set; }
        public DateTime PackBeginDate { get; set; }
        public DateTime PackEndDate { get; set; }
        public ObservableCollection<string> PackMsgs { get; } = new ObservableCollection<string>();
        public DbHelper mDbHelper;


        public DbViewerModel() {

        }
        public void Init() {
            if (!Load())
                Save();
            mDbHelper = new DbHelper();
            mDbHelper.DbDirPath = DbDirPath;
            mDbHelper.Init();
        }
        private string filePath = "param.json";
        bool Load() {
            return DbViewerModelJsonDb.Load(this, filePath);
        }
        public bool Save()
        {
            return DbViewerModelJsonDb.Save(this, filePath);
        }
    
        

    }

    public class DbViewerModelJsonDb 
    {
        static Mapper Mapper { get; } = new AutoMapper.Mapper(new MapperConfiguration(c =>
        {
            c.CreateMap<DbViewerModel, DbViewerModelJsonDb>().ReverseMap();
        }));
        public static bool Save(DbViewerModel src, string filePath)
        {
            var p = Mapper.Map<DbViewerModelJsonDb>(src);
            try
            {
                File.WriteAllText(filePath, JsonConvert.SerializeObject(p, Formatting.Indented));
            }
            catch
            {
                //异常,没有json 编码失败
                return false;
            }
            return true;
        }
        public static bool Load(DbViewerModel src, string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    string json = File.ReadAllText(filePath);
                    var p = JsonConvert.DeserializeObject<DbViewerModelJsonDb>(json);
                    Mapper.Map(p, src);
                    return true;
                }
            }
            catch
            {
                //异常,没有json 解码失败
            }
            return false;
        }
        public string DbDirPath { get; set; } = @"D:\blowingdata";
    }
}