using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Extensions.Logging;
using ProjectLibrary.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectLibrary.Reports;

public class ChartReport
{
    private readonly IOrderRepository _orderRepository;
    private readonly ILogger<ChartReport> _logger;
    public ChartReport(IOrderRepository orderRepository, ILogger<ChartReport> logger)
    {
        _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }
    public bool CreateChart(string filePath, DateTime dateTime)
    {
        try
        {
            new PdfBuilder(filePath)
            .AddHeader("Количество книг в библиотеках")
            .AddPieChart($"Библиотеки на {dateTime: dd MMMM yyyy}", GetData(dateTime))
            .Build();
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Ошибка при формировании документа");
            return false;
        }
    }

    private List<(string Caption, double Value)> GetData(DateTime? dateTime = null)
    {
        return _orderRepository
            .ReadOrders()
            .GroupBy(x => x.BookOrders.First(y => y.OrderID == x.Id).BookName , (key, group) => new { Name = key, Count = group.Sum(y => y.BookOrders.First(z => z.OrderID == y.Id).Count) })
            .Select(x => (x.Name, (double)x.Count))
            .ToList();
    }
}