using FrontendWebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace FrontendWebApi.ApiControllers
{
    public class LightScheduleController : MyBaseApiController<LightScheduleController>
    {
        private readonly IBackendRepository backendRepository;
        private readonly IFrontendRepository frontendRepository;

        public LightScheduleController
        (
            IBackendRepository backendRepository,
            IFrontendRepository frontendRepository
        )
        {
            this.backendRepository = backendRepository;
            this.frontendRepository = frontendRepository;
        }

        [HttpPost]
        [Route("api/LightSchedule/GetLightDevice")]
        public async Task<ActionResult<ApiResult<List<lightDevice>>>> GetLightDevice(GetDevicePost post)
        {
            List<lightDevice> lightDevices = new List<lightDevice>();
            ApiResult<List<lightDevice>> apiResult = new ApiResult<List<lightDevice>>();
            try
            {
                lightDevices = await backendRepository.GetAllAsync<lightDevice>($@"
                select * from device where building_guid = '{post.building_guid}' and sub_system_guid = '{post.sub_system_guid}' and floor_guid = '{post.floor_guid}' and deleted = 0 and status = 0 order by priority
                ");
                
                if(!String.IsNullOrEmpty(post.schedule_guid))
                {
                    var devicechecklist = await backendRepository.GetAllAsync<string>(@$"
                    select sd.device_guid from schedule_device sd where light_schedule_guid = '{post.schedule_guid}'
                    ");
                    foreach(var a in lightDevices)
                    {
                        if(devicechecklist.Contains(a.device_guid))
                        {
                            a.check = 1;
                        }
                        else
                        {
                            a.check = 0;
                        }
                    }
                }


                apiResult.Code = "0000";
                apiResult.Data = lightDevices;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/LightSchedule/SaveSchedule")]
        public async Task<ActionResult<ApiResult<string>>> SaveSchedule (SaveSchedule saveSchedule)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                if(String.IsNullOrEmpty(saveSchedule.light_schedule_guid))
                {
                    Dictionary<string, object> Schedule = new Dictionary<string, object>();
                    var newguid = Guid.NewGuid();
                    Schedule = new Dictionary<string, object>()
                    {
                        { "@light_schedule_guid", newguid},
                        { "@status", saveSchedule.status},
                        { "@full_name", saveSchedule.full_name},
                        { "@week", saveSchedule.week},
                        { "@cycle", saveSchedule.cycle},
                        { "@floor_guid", saveSchedule.floor_guid},
                        { "@start_time", saveSchedule.start_time},
                        { "@end_time", saveSchedule.end_time},
                        { "@created_by", myUser.userinfo_guid}
                    };
                    await backendRepository.AddOneByCustomTable(Schedule, "light_schedule");
                    List<Dictionary<string, object>> ScheduleDevices = new List<Dictionary<string, object>>();
                    foreach (var a in saveSchedule.devicelist)
                    {
                        Dictionary<string, object> ScheduleDevice = new Dictionary<string, object>();
                        ScheduleDevice = new Dictionary<string, object>()
                        {
                            { "@light_schedule_guid", newguid},
                            { "@device_guid", a}
                        };
                        ScheduleDevices.Add(ScheduleDevice);
                    }
                    await backendRepository.AddMutiByCustomTable(ScheduleDevices, "schedule_device");
                }
                else
                {
                    Dictionary<string, object> Schedule = new Dictionary<string, object>();
                    Schedule = new Dictionary<string, object>()
                    {
                        { "@status", saveSchedule.status},
                        { "@full_name", saveSchedule.full_name},
                        { "@week", saveSchedule.week},
                        { "@cycle", saveSchedule.cycle},
                        { "@floor_guid", saveSchedule.floor_guid},
                        { "@start_time", saveSchedule.start_time},
                        { "@end_time", saveSchedule.end_time},
                        { "@updated_by", myUser.userinfo_guid},
                        { "@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}
                    };
                    await backendRepository.UpdateOneByCustomTable(Schedule, "light_schedule", $" light_schedule_guid = '{saveSchedule.light_schedule_guid}'");
                    await backendRepository.PurgeOneByGuidWithCustomDBNameAndTable("schedule_device", $" light_schedule_guid = '{saveSchedule.light_schedule_guid}'");
                    List<Dictionary<string, object>> ScheduleDevices = new List<Dictionary<string, object>>();
                    foreach (var a in saveSchedule.devicelist)
                    {
                        Dictionary<string, object> ScheduleDevice = new Dictionary<string, object>();
                        ScheduleDevice = new Dictionary<string, object>()
                        {
                            { "@light_schedule_guid", saveSchedule.light_schedule_guid},
                            { "@device_guid", a}
                        };
                        ScheduleDevices.Add(ScheduleDevice);
                    }
                    await backendRepository.AddMutiByCustomTable(ScheduleDevices, "schedule_device");
                }
                apiResult.Code = "0000";
                apiResult.Data = "成功";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }


        [HttpPost]
        [Route("api/LightSchedule/ScheduleTable")]
        public async Task<ActionResult<ApiResult<List<ScheduleTable>>>> GetLightDevice(listfloors post)
        {
            List<ScheduleTable> ScheduleTable = new List<ScheduleTable>();
            ApiResult<List<ScheduleTable>> apiResult = new ApiResult<List<ScheduleTable>>();
            try
            {
                ScheduleTable = await backendRepository.GetAllAsync<ScheduleTable>($@"
                    select  ls.*,sd.devicecount from light_schedule ls
                    left join (select sd.light_schedule_guid, COUNT(*) devicecount from schedule_device sd group by sd.light_schedule_guid) sd on sd.light_schedule_guid = ls.light_schedule_guid
                    where ls.floor_guid in @floors and ls.deleted = 0
                    ",new { floors = post.Floors});
                apiResult.Code = "0000";
                apiResult.Data = ScheduleTable;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/LightSchedule/GetOneschedule")]
        public async Task<ActionResult<ApiResult<Schedule>>> GetOneschedule(string schedule_guid)
        {
            ApiResult<Schedule> apiResult = new ApiResult<Schedule>();
            try
            {
                var OneScheduleTable = await backendRepository.GetOneAsync<Schedule>($@"
                select * from light_schedule where light_schedule_guid = '{schedule_guid}'
                ");
                apiResult.Code = "0000";
                apiResult.Data = OneScheduleTable;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/LightSchedule/DeleteSchedule")]
        public async Task<ActionResult<ApiResult<string>>> DeleteSchedule(string schedule_guid)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                await backendRepository.DeleteOne(schedule_guid, "light_schedule", "light_schedule_guid");
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        [Route("api/LightSchedule/SendAPI")]
        public async Task<ActionResult<ApiResult<string>>> SendAPI(string guid)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                var TimeNow = DateTime.Now.ToString("dddd HH:mm");
                var oneSchedule = await backendRepository.GetOneAsync<Schedule>("light_schedule", $" light_schedule_guid = '{guid}'");
                var weeklistN = oneSchedule.week.Split(',');
                List<string> weeklist = new List<string>();
                foreach (var weekN in weeklistN)
                {
                    var week = weekN switch
                    {
                        "0" => "星期日",
                        "1" => "星期一",
                        "2" => "星期二",
                        "3" => "星期三",
                        "4" => "星期四",
                        "5" => "星期五",
                        "6" => "星期六",
                        _ => ""
                    };
                    weeklist.Add(week);
                }
                var Time = TimeNow.Split(" ");
                string check = "<real val='false' />";
                if(DateTime.Parse(Time[1])> DateTime.Parse(oneSchedule.start_time) && DateTime.Parse(Time[1]) <= DateTime.Parse(oneSchedule.end_time) && weeklist.Contains(Time[0]))
                {
                    check = "<real val='true' />";
                }
                else
                {
                    check = "<real val='false' />";
                }

                var deviceNumList = await backendRepository.GetAllAsync<string>(@$"select d.device_number from schedule_device sd left join device d on sd.device_guid = d.device_guid
                                                                                where light_schedule_guid = '{guid}'");

                foreach(var deviceNum in deviceNumList)
                {
                    var d = deviceNum.Split("_");
                    var html = "http://greencloud.fic.com.tw:8080/obix/config/Arena/"+$"{d[0]}/{d[1]}/{d[2]}/{d[3]}/{deviceNum}/SSC/set";
                    string authInfo = "AR_Light" + ":" + "Light12345";
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(html);
                    request.Method = "POST";
                    request.Accept = "application/json; charset=utf-8";
                    request.Headers["Authorization"] = "Basic " + authInfo;
                    byte[] byteArray = Encoding.UTF8.GetBytes(check);
                    using (Stream reqStream = request.GetRequestStream())
                    {
                        reqStream.Write(byteArray, 0, byteArray.Length);
                    }
                    var response = (HttpWebResponse)request.GetResponse();
                    string strResponse = "";

                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        strResponse = sr.ReadToEnd();
                    }
                }

                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return Ok(apiResult);
        }
    }
}