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 StatsByDzService : IStatsByDzService
    {
        #region Public Constructors

        public StatsByDzService(IJumpService jumpService,
                                IIdentityService identityService,
                                IStatsByDzRepository statsByDzRepository)
        {
            _jumpService = jumpService;
            _identityService = identityService;
            _statsByDzRepository = statsByDzRepository;
        }

        #endregion Public Constructors

        #region Public Methods

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

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

                _statsByDzRepository.Add(results);
                return results;
            }

            return allStats;
        }

        /// <summary>
        /// Resets the drop zone statistics.
        /// </summary>
        public void Reset()
        {
            _statsByDzRepository.Delete(_identityService.ConnectedUser);
        }

        #endregion Public Methods

        #region Private Fields

        private readonly IIdentityService _identityService;
        private readonly IJumpService _jumpService;
        private readonly IStatsByDzRepository _statsByDzRepository;

        #endregion Private Fields
    }
}
