using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace Fast.Web.Logic.ReportSources;

class PlantStatements : ReportSourceBase
{
    public PlantStatements(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()
    {
        var query = (from q in db.VwRptPlantStatements select q);

        string paramName;

        paramName = "Meter";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            query = query.Where(x => x.MeterId.HasValue && idList.Contains(x.MeterId.Value));
        }

        paramName = "Plant";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            query = query.Where(x => x.PlantId.HasValue && idList.Contains(x.PlantId.Value));
        }

        paramName = "Producer";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            query = query.Where(x => x.ProducerId.HasValue && idList.Contains(x.ProducerId.Value));
        }

        paramName = "Production Month";
        if (HasParam(paramName))
        {
            var exp = GetDateRangeExpression<VwRptPlantStatement>(paramName, "ProductionMonth", false);
            query = query.Where(exp);
        }

        var result = await query.ToListAsync();
        FillSheet("Plant Statement", result);

        return GetNewFilterParams();
    }
}
