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 StatsByJumpTypeService : IStatsByJumpTypeService
    {
        #region Public Constructors

        public StatsByJumpTypeService(IJumpService jumpService,
                                      IIdentityService identityService,
                                      IStatsByJumpTypeRepository statsByJumpTypeRepository)
        {
            _jumpService = jumpService;
            _identityService = identityService;
            _statsByJumpTypeRepository = statsByJumpTypeRepository;
        }

        #endregion Public Constructors

        #region Public Methods

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

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

                _statsByJumpTypeRepository.Add(results);
                return results;
            }

            return allStats;
        }

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

        #endregion Public Methods

        #region Private Fields

        private readonly IIdentityService _identityService;
        private readonly IJumpService _jumpService;
        private readonly IStatsByJumpTypeRepository _statsByJumpTypeRepository;

        #endregion Private Fields
    }
}
