using System;
using System.Collections.Generic;
using System.Linq;
namespace Schaad.Accounting.Models
{
///
/// What the charts on the Strom and Wasser pages show: how the bills are grouped (calendar year
/// by default) and which years. A null / means from the first/to the last
/// year with a bill, so a newly added bill shows up without touching the filter.
///
public record BillChartFilter(BillPeriodKind Kind = BillPeriodKind.Year, int? FromYear = null, int? ToYear = null)
{
/// The years any bill touches, from the first to the last; empty without bills.
public static List YearsOf(IEnumerable bills) where T : IPeriodBill
{
var list = bills.ToList();
if (list.Count == 0)
{
return [];
}
var first = list.Min(b => b.PeriodFrom.Year);
var last = list.Max(b => b.PeriodTo.Year);
return Enumerable.Range(first, Math.Max(last - first, 0) + 1).ToList();
}
/// The selected years, clamped to (which must not be empty).
public (int From, int To) RangeIn(IReadOnlyList years)
{
var from = Math.Clamp(FromYear ?? years[0], years[0], years[^1]);
var to = Math.Clamp(ToYear ?? years[^1], years[0], years[^1]);
return from <= to ? (from, to) : (to, from);
}
/// True if the filter covers all of .
public bool CoversAll(IReadOnlyList years) => RangeIn(years) == (years[0], years[^1]);
///
/// Groups the bills by and keeps the periods that overlap the selected
/// years. A bill (or calendar period) reaching into the range is kept whole, e.g. the bill
/// 1.7.2023–30.6.2024 for the range 2024–2024.
///
public List> Apply(IEnumerable bills) where T : class, IPeriodBill, new()
{
var list = bills.ToList();
var years = YearsOf(list);
if (years.Count == 0)
{
return [];
}
var (from, to) = RangeIn(years);
return BillPeriod.FromBills(list, Kind)
.Where(p => p.From.Year <= to && p.To.Year >= from)
.ToList();
}
}
}