using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using VIZ.Framework.Module;

namespace VIZ.Framework.ImageContrastTool
{
    /// <summary>
    /// 应用程序启动 -- 初始化LiteDb
    /// </summary>
    public class AppSetup_InitLiteDb : AppSetupBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(AppSetup_InitLiteDb));

        /// <summary>
        /// 描述
        /// </summary>
        public override string Detail { get; } = "应用程序启动 -- 初始化LiteDb";

        /// <summary>
        /// 执行启动
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        /// <returns>是否成功执行</returns>
        public override bool Setup(AppSetupContext context)
        {
            string floder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "db");
            if (!System.IO.Directory.Exists(floder))
            {
                System.IO.Directory.CreateDirectory(floder);
            }
            string path = System.IO.Path.Combine(floder, "cache.db");

            ApplicationDomainEx.LiteDbContext = new LiteDbContext(path);

            // 初始化系统配置
            this.initSystemConfig();

            return true;
        }

        /// <summary>
        /// 执行关闭
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        public override void Shutdown(AppSetupContext context)
        {
            ApplicationDomainEx.LiteDbContext?.Dispose();
            ApplicationDomainEx.LiteDbContext = null;
        }

        /// <summary>
        /// 初始化系统配置
        /// </summary>
        private void initSystemConfig()
        {
            SystemConfig config = ApplicationDomainEx.LiteDbContext.SystemConfigs.FindAll().FirstOrDefault();
            if (config == null)
            {
                config = new SystemConfig();
                ApplicationDomainEx.LiteDbContext.SystemConfigs.Insert(config);
            }
        }
    }
}
