using Microsoft.Extensions.Logging;
using Quartz;
using SolarPower.Models.PowerStation;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SolarPower.Quartz.Jobs
{
    [DisallowConcurrentExecution]
    public class CalcInverter15minJob : IJob
    {
        private readonly ILogger<CalcInverter15minJob> logger;
        private readonly IPowerStationRepository powerStationRepository;

        public CalcInverter15minJob(ILogger<CalcInverter15minJob> logger, IPowerStationRepository powerStationRepository)
        {
            this.logger = logger;
            this.powerStationRepository = powerStationRepository;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                //var day_array = new string[] { "15", "16", "17", "18", "19" };
                ////var day_array = new string[] { "15" };
                //var time_array = new string[] { "00:02", "00:17", "00:32", "00:47",
                //                                "01:02", "01:17", "01:32", "01:47",
                //                                "02:02", "02:17", "02:32", "02:47",
                //                                "03:02", "03:17", "03:32", "03:47",
                //                                "04:02", "04:17", "04:32", "04:47",
                //                                "05:02", "05:17", "05:32", "05:47",
                //                                "06:02", "06:17", "06:32", "06:47",
                //                                "07:02", "07:17", "07:32", "07:47",
                //                                "08:02", "08:17", "08:32", "08:47",
                //                                "09:02", "09:17", "09:32", "09:47",
                //                                "10:02", "10:17", "10:32", "10:47",
                //                                "11:02", "11:17", "11:32", "11:47",
                //                                "12:02", "12:17", "12:32", "12:47",
                //                                "13:02", "13:17", "13:32", "13:47",
                //                                "14:02", "14:17", "14:32", "14:47",
                //                                "15:02", "15:17", "15:32", "15:47",
                //                                "16:02", "16:17", "16:32", "16:47",
                //                                "17:02", "17:17", "17:32", "17:47",
                //                                "18:02", "18:17", "18:32", "18:47",
                //                                "19:02", "19:17", "19:32", "19:47",
                //                                "20:02", "20:17", "20:32", "20:47",
                //                                "21:02", "21:17", "21:32", "21:47",
                //                                "22:02", "22:17", "22:32", "22:47",
                //                                "23:02", "23:17", "23:32", "23:47",
                //};

                #region step1. 找出所有電站
                logger.LogInformation("【CalcInverter15minJob】【開始取得電站資料】");
                var powerStations = await powerStationRepository.GetAllAsync();
                logger.LogInformation("【CalcInverter15minJob】【取得成功電站資料】");
                logger.LogInformation("【CalcInverter15minJob】【電站資料】 - {0}", System.Text.Json.JsonSerializer.Serialize(powerStations));
                #endregion

                List<InverterHistory> calcInverter15mins = new List<InverterHistory>();

                var DateTimeNow = DateTime.Now;


                var dateNowTime = DateTimeNow.ToString("yyyy-MM-dd HH:mm");

                //for (var i = 0; i < day_array.Count(); i++)
                //{
                //    for (var j = 0; j < time_array.Count(); j++)
                //    {
                        //var dateNowTime = string.Format("2021-07-{0} {1}", day_array[i], time_array[j]);

                        #region step2. 從電站的DB及電站編號找出該電站的控制器
                        foreach (var powerStation in powerStations)
                        {



                            //取得所有該電站的逆變器
                            logger.LogInformation("【CalcInverter15minJob】【開始取得電站[{0}]在{1}的逆變器設備資訊】", powerStation.Code, dateNowTime);
                            var controllers = await powerStationRepository.GetAllDeviceControllerId(powerStation.Id, powerStation.SiteDB);
                            var inverters = await powerStationRepository.InverterTable(controllers, powerStation.SiteDB);
                            var inverterIds = inverters.Where(x => x.Enabled == 1 && x.Status != 0).Select(x => x.InverterId).ToList();
                            logger.LogInformation("【CalcInverter15minJob】【取得成功電站[{0}]在{1}的逆變器設備資訊】", powerStation.Code, dateNowTime);

                            var calcInverter15min = new InverterHistory();

                            #region step2-1. 計算該電站逆變器每15min 的值
                            var table_name = String.Format("s{1}01_inv", powerStation.SiteDB, powerStation.Code);
                            var full_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, table_name);
                            var exist = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);

                            if (!string.IsNullOrEmpty(exist))
                            {
                                logger.LogInformation("【CalcInverter15minJob】【開始計算電站[{0}]在{1}的每15分鐘逆變器資訊】", powerStation.Code, dateNowTime);
                                calcInverter15mins = await powerStationRepository.CalcInverterHisyort15minData(dateNowTime, powerStation.SiteDB, full_table_name, inverterIds);
                                logger.LogInformation("【CalcInverter15minJob】【計算完成電站[{0}]在{1}的每15分鐘逆變器資訊】", powerStation.Code, dateNowTime);
                                if (calcInverter15mins.Count() > 0)
                                {
                                    foreach (var inverterHistory in calcInverter15mins)
                                    {
                                        inverterHistory.TIMESTAMP = Convert.ToDateTime(inverterHistory.TIMESTAMP + ":00").ToString("yyyy-MM-dd HH:mm:ss");
                                        inverterHistory.PowerStationId = powerStation.Id;
                                    }
                                }
                            }

                            
                            #endregion

                          
                        }
                        #endregion

                        #region step3. 將 inverter INSERT 到 inverter_history_hour 資料表
                        List<string> inverter_history_properties = new List<string>()
                        {
                            "PowerStationId",
                            "INVERTERID",
                            "TIMESTAMP",
                            "KWH",
                            "TODAYKWH",
                            "KWHKWP",
                        };

                        await powerStationRepository.AddInverter15minHistory(calcInverter15mins, inverter_history_properties);
                        #endregion
                //    }
                //}



            }
            catch (Exception exception)
            {
                logger.LogError("【{0}】{1}", "CalcInverter15minJob", exception.Message);
            }
        }
    }
}
