using DocumentFormat.OpenXml.Packaging;
using Fast.Web.Logic.GasControl;
using Fast.Models;

namespace Fast.Web.Logic.ReportSources;

class SosData : ReportSourceBase
{
    public SosData(MyDbContext context, SpreadsheetDocument wb, string reportName, int dataSourceId, int filterId, string filterName, List<ReportFilterParameter> filterParams, int userInfoId)
        : base(context, wb, reportName, dataSourceId, filterId, filterName, filterParams, userInfoId) { }

    public override async Task<List<ReportFilterParameter>> Run()
    {
        string paramName;

        paramName = "Gas Day";
        if (!HasParam(paramName))
        {
            var dateRange = new DateRange(Enums.DateStyle.DateRange, Util.Date.FirstDayOfMonth(DateTime.Today), Util.Date.LastDayOfMonth(DateTime.Today));
            AddDateRangeParam(paramName, dateRange);
        }

        var dateRanges = GetDateRanges(Enums.DateStyle.DateRange, "Gas Day");
        var allGasExportItems = new List<GasTrackExportItem>();
        var gasExporter = new GasTrackExporter();
        foreach (var dateRange in dateRanges)
        {
            var gasExportList = await gasExporter.CreateExportList(dateRange.FromDate, dateRange.ToDate);
            allGasExportItems.AddRange(gasExportList);
        }

        List<int>? marketPipeIds = null;
        paramName = "Market Pipeline";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            marketPipeIds = GetIdList(paramName);
        }

        var allSosDataItems = new List<SosDataItem>();
        foreach (var gasExportItem in allGasExportItems)
        {
            if (marketPipeIds != null && !marketPipeIds.Contains(gasExportItem.sPIPELINE_ID))
                continue;

            var sosDataItem = new SosDataItem(gasExportItem);
            allSosDataItems.Add(sosDataItem);
        }

        FillSheet("SOS Data", allSosDataItems);

        return GetNewFilterParams();
    }
}
