using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using InABox.Core;
using InABox.WPF;

namespace InABox.DynamicGrid;

public class DynamicGridDurationAggregate : IDynamicGridSummaryAggregate
{
    public int Count { get; private set; }

    public TimeSpan Sum { get; private set; }

    public Action<IEnumerable, string, PropertyDescriptor> CalculateAggregateFunc()
    {
        return CalculateAggregate;
    }

    private void CalculateAggregate(IEnumerable items, string property, PropertyDescriptor args)
    {
        if (items is IEnumerable<DataRowView> rows)
        {
            if (string.Equals(args.Name, "Count"))
            {
                Count = rows.Count();
            }
            else if (string.Equals(args.Name, "Sum"))
            {
                Sum = new TimeSpan();
                foreach (var row in rows)
                    if (row[property] is TimeSpan t)
                        Sum += t;
            }
        }
        else
        {
            Logger.Send(LogType.Error, "", $"Attempting to calculate aggregate on invalid data type '{items.GetType()}'.");
        }
    }

    public string Format(String command, String format)
    {
        if (string.Equals(command, "Sum"))
            return string.IsNullOrWhiteSpace(format) || string.Equals(format, "hh':'mm")
                ? Math.Truncate(Sum.TotalHours).ToString("#00") + ":" + Sum.Minutes.ToString("D2")
                : new TimeSpanToStringConverter(format).Convert(Sum);
                
        if (string.Equals(command, "Count"))
            return string.Format(format, Count);

        return "";
    }
}