using ReportingServices.Shared.HelperClasses;
using ReportingServices.Shared.Models.ProductionReport;
using ReportingServices.Shared.ViewModels.ProductionReport;
using System.Text.Json;
using System.Web;

namespace ReportingServices.Shared.Repositories
{
    public class FabTimeReportingRepository : IFabTimeReportingRepository
    {
        private readonly string _toolFilter = "~R76%2C%20~R78%2C%20~R25%2C%20~R67%2C%20~R69%2C%20~R71%2C%20~R47%2C%20~R51%2C%20~R28";

        public async Task<List<ReactorOutsByRDS>> GetMovesTrendData(string startDate = "", string endDate = "")
        {
            string url = APIHelperFunctions.GenerateURLWithParameters(startDate: startDate, endDate: endDate, chart: "MOVESLOTLIST", areasLike: "CLEANROOM", operationsLike: "1UNLOAD");

            return await GetJsonData<List<ReactorOutsByRDS>>(url);
        }

        public async Task<List<EquipmentStateByDay>> GetToolStateTrendData(string toolType)
        {
            string url = APIHelperFunctions.GenerateURLWithParameters(chart: "TOOLSTATE", periodLen: "24", capacityTypesLike: toolType, toolsLike: _toolFilter);

            return await GetJsonData<List<EquipmentStateByDay>>(url);
        }

        public async Task<List<ToolStateCurrent>> GetToolStateData(string toolType)
        {
            string capacityFilter = toolType == "ASM" ? toolType + "%2CASM%2B" : toolType;
            string startDate = HttpUtility.UrlEncode(APIHelperFunctions.GetDateWithOffsetAsAPIString(DateTime.Now.ToString(), -12.5f));

            string url = APIHelperFunctions.GenerateURLWithParameters(chart: "ToolStateGantt", periodLen: "24",
                capacityTypesLike: capacityFilter, toolsLike: _toolFilter, startDate: startDate);

            return await GetJsonData<List<ToolStateCurrent>>(url);
        }

        public async Task<T> GetJsonData<T>(string url)
        {
            T deserializedJson;

            using (var client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    deserializedJson = JsonSerializer.Deserialize<T>(apiResponse);
                }
            }

            return deserializedJson;
        }


    }
}
