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

namespace Fast.Web.Logic.ReportSources;

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

    public override async Task<List<ReportFilterParameter>> Run()
    {
        var query = (from q in db.VwRptMeterData select q);

        string paramName;

        paramName = "Active/Inactive";
        if (HasParam(paramName))
        {
            var isActiveOnly = GetIsActiveValue(paramName);
            var currentDateOnly = DateOnly.FromDateTime(DateTime.UtcNow);
            if (isActiveOnly)
                query = query.Where(x => !x.InactiveDate.HasValue || x.InactiveDate.Value > currentDateOnly);
            else
                query = query.Where(x => x.InactiveDate.HasValue && x.InactiveDate.Value <= currentDateOnly);
        }

        query = query.OrderBy(x => x.MeterName).ThenByDescending(x => x.InactiveDate);
        var result = await query.ToListAsync();

        paramName = "Point/Hub";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            result = result.Where(x => x.PointIds != null && x.PointIds.Split(',').Any(y => idList.Contains(int.Parse(y)))).ToList();
        }

        paramName = "Product";
        if (HasParam(paramName))
        {
            await FixInvalidFilterParams(paramName);
            var idList = GetIdList(paramName);
            result = result.Where(x => x.ProductIds != null && x.ProductIds.Split(',').Any(y => idList.Contains(int.Parse(y)))).ToList();
        }

        FillSheet("Meter Data", result);

        return GetNewFilterParams();
    }

}


