using Backend.Services.Implement;
using Microsoft.Extensions.Logging;
using Quartz;
using Repository.BackendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BackendWorkerService.Quartz.Jobs
{
    /// <summary>
    /// 定時將資料表加入派送任務
    /// </summary>
    [DisallowConcurrentExecution]
    class RegularUpdateDBTableJob: IJob
    {
        private readonly ILogger<RegularUpdateDBTableJob> logger;
        private readonly IBackgroundServiceRepository backgroundServiceRepository;
        private readonly IBackendRepository backendRepository;

        public RegularUpdateDBTableJob(
            ILogger<RegularUpdateDBTableJob> logger,
            IBackgroundServiceRepository backgroundServiceRepository,
            IBackendRepository backendRepository)
        {
            this.logger = logger;
            this.backgroundServiceRepository = backgroundServiceRepository;
            this.backendRepository = backendRepository;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                logger.LogInformation("【RegularUpdateDBTableJob】【任務開始】");

                //要派送的資料表
                List<string> db_tables = new List<string>() { "variable" };

                foreach (var db_table in db_tables)
                {
                    try
                    {
                        logger.LogInformation("【RegularUpdateDBTableJob】【新增資料表 [{0}] 至派送任務】", db_table);
                        //取得資料表所有資料
                        var temp_datas = (await backgroundServiceRepository.GetAllAsync<dynamic>(db_table, ""));

                        List<Dictionary<string, object>> dicts = new List<Dictionary<string, object>>();
                        foreach (var temp_data in temp_datas)
                        {
                            var dict = new Dictionary<string, object>((IDictionary<string, object>)temp_data);

                            dicts.Add(dict);
                        }

                        await backendRepository.ManualInsertBackgroundServiceTask("", "", db_table, "purge_all_insert", dicts);

                        logger.LogError("【RegularUpdateDBTableJob】【新增成功 資料表 [{0}] 至派送任務】", db_table);
                    }
                    catch(Exception exception)
                    {
                        logger.LogError("【RegularUpdateDBTableJob】【新增失敗 資料表 [{0}] 至派送任務】", db_table);
                        logger.LogError("【RegularUpdateDBTableJob】【新增失敗 資料表 [{0}] 至派送任務】[Exception]:{1}", db_table, exception.ToString());
                    }
                }
            }
            catch (Exception exception)
            {
                logger.LogError("【RegularUpdateDBTableJob】【任務失敗】");
                logger.LogError("【RegularUpdateDBTableJob】【任務失敗】[Exception]:{0}", exception.ToString());
            }

        }
    }
}