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

namespace skydiveLogs_api.DomainBusiness
{
    public class StatsByGearService : IStatsByGearService
    {
        #region Public Constructors

        public StatsByGearService(IJumpService jumpService,
                                  IIdentityService identityService,
                                  IStatsByGearRepository statsByGearRepository)
        {
            _jumpService = jumpService;
            _identityService = identityService;
            _statsByGearRepository = statsByGearRepository;
        }

        #endregion Public Constructors

        #region Public Methods

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

                if (allJumps.Any())
                {
                    results = [.. allJumps.GroupBy(j => $"{j.Gear.Name} / {j.Gear.MainCanopy}",
                                                   j => j,
                                                   (groupby, jumps) => new StatsByGear
                                                   {
                                                       Gear = groupby.ToString(),
                                                       Nb = jumps.Count(),
                                                       User = _identityService.ConnectedUser
                                                   })];
                }

                _statsByGearRepository.Add(results);
                return results;
            }

            return allStats;
        }

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

        #endregion Public Methods

        #region Private Fields

        private readonly IIdentityService _identityService;
        private readonly IJumpService _jumpService;
        private readonly IStatsByGearRepository _statsByGearRepository;

        #endregion Private Fields
    }
}
