using System;
using System.Collections.Generic;
using System.Linq;
namespace Schaad.Accounting.Models
{
///
/// One calendar half-year (January–June or July–December) of electricity bills, for the
/// charts on the Strom page. holds the bill values that fall into this
/// half-year, or is null if no bill covers it.
///
public class ElectricityHalfYear
{
public DateOnly From { get; init; }
public ElectricityBill Bill { get; init; }
/// Short label for a chart axis, e.g. "H2 23".
public string Label => $"H{(From.Month <= 6 ? 1 : 2)} {From:yy}";
///
/// Splits the bills into calendar half-years, from the first to the last covered one
/// (half-years in between that no bill covers are included with a null Bill). A bill's
/// values are spread evenly over the months of its period, so a yearly bill (1 July –
/// 30 June) contributes exactly half to each of its two half-years.
///
public static List FromBills(IEnumerable bills)
{
var sums = new SortedDictionary();
foreach (var bill in bills)
{
var months = MonthIndex(bill.PeriodTo) - MonthIndex(bill.PeriodFrom) + 1;
if (months <= 0)
{
continue;
}
var monthsPerHalf = Enumerable.Range(0, months)
.Select(m => HalfYearStart(bill.PeriodFrom.AddMonths(m)))
.GroupBy(start => start);
foreach (var half in monthsPerHalf)
{
var share = (decimal)half.Count() / months;
if (!sums.TryGetValue(half.Key, out var sum))
{
sum = new ElectricityBill { PeriodFrom = half.Key, PeriodTo = half.Key.AddMonths(6).AddDays(-1) };
sums[half.Key] = sum;
}
sum.GridKwh += bill.GridKwh * share;
sum.PvKwh += bill.PvKwh * share;
sum.GridChf += bill.GridChf * share;
sum.PvChf += bill.PvChf * share;
sum.SideCostsChf += bill.SideCostsChf * share;
}
}
var result = new List();
if (sums.Count == 0)
{
return result;
}
for (var start = sums.Keys.First(); start <= sums.Keys.Last(); start = start.AddMonths(6))
{
result.Add(new ElectricityHalfYear { From = start, Bill = sums.GetValueOrDefault(start) });
}
return result;
}
private static int MonthIndex(DateOnly date) => date.Year * 12 + date.Month - 1;
private static DateOnly HalfYearStart(DateOnly date) => new(date.Year, date.Month <= 6 ? 1 : 7, 1);
}
}