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 StatsByYearByJumpTypeService : IStatsByYearByJumpTypeService
    {
        #region Public Constructors

        public StatsByYearByJumpTypeService(IJumpService jumpService,
                                            IIdentityService identityService,
                                            IStatsByYearByJumpTypeRepository statsByYearByJumpTypeRepository)
        {
            _jumpService = jumpService;
            _identityService = identityService;
            _statsByYearByJumpTypeRepository = statsByYearByJumpTypeRepository;
        }

        #endregion Public Constructors

        #region Public Methods

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

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

                _statsByYearByJumpTypeRepository.Add(results);
                return results;
            }

            return allStats;
        }

        /// <summary>
        /// Resets the last year by jump type statistics.
        /// </summary>
        public void Reset()
        {
            _statsByYearByJumpTypeRepository.Delete(_identityService.ConnectedUser);
        }

        #endregion Public Methods

        #region Private Fields

        private readonly IIdentityService _identityService;
        private readonly IJumpService _jumpService;
        private readonly IStatsByYearByJumpTypeRepository _statsByYearByJumpTypeRepository;

        #endregion Private Fields
    }
}
