using skydiveLogs_api.Domain;
using skydiveLogs_api.DomainBusiness.Interfaces;
using skydiveLogs_api.DomainService.Repositories;
using System.Collections.Generic;
using System.Linq;

namespace skydiveLogs_api.DomainBusiness
{
    public class StatsByYearService : IStatsByYearService
    {
        #region Public Constructors

        public StatsByYearService(IJumpService jumpService,
                                  IIdentityService identityService,
                                  IStatsByYearRepository statsByYearRepository)
        {
            _jumpService = jumpService;
            _identityService = identityService;
            _statsByYearRepository = statsByYearRepository;
        }

        #endregion Public Constructors

        #region Public Methods

        /// <summary>
        /// Retrieves statistics grouped by year.
        /// </summary>
        /// <returns>A collection of StatsByYear entities containing the statistics.</returns>
        public IEnumerable<StatsByYear> GetStats()
        {
            var allStats = _statsByYearRepository.GetAll(_identityService.ConnectedUser);
            if (!allStats.Any())
            {
                var allJumps = _jumpService.GetAllJumps();
                var results = new List<StatsByYear>();

                if (allJumps.Any())
                {
                    results = [.. allJumps.GroupBy(j => j.JumpDate.Year,
                                                   j => j,
                                                   (groupby, jumps) => new StatsByYear
                                                   {
                                                       Year = groupby.ToString(),
                                                       Nb = jumps.Count(),
                                                       User = _identityService.ConnectedUser
                                                   })];
                }

                _statsByYearRepository.Add(results);
                return results;
            }

            return allStats;
        }

        /// <summary>
        /// Resets the year statistics.
        /// </summary>
        public void Reset()
        {
            _statsByYearRepository.Delete(_identityService.ConnectedUser);
        }

        #endregion Public Methods

        #region Private Fields

        private readonly IIdentityService _identityService;
        private readonly IJumpService _jumpService;
        private readonly IStatsByYearRepository _statsByYearRepository;

        #endregion Private Fields
    }
}
