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

namespace skydiveLogs_api.DomainBusiness
{
    public class TunnelService : ITunnelService
    {
        #region Public Constructors

        public TunnelService(IDropZoneRepository dropZoneRepository,
                             IDropZoneService dropZoneService,
                             ICacheService cacheService)
        {
            _dropZoneRepository = dropZoneRepository;
            _dropZoneService = dropZoneService;
            _cacheService = cacheService;
        }

        #endregion Public Constructors

        #region Public Methods

        /// <summary>
        /// Retrieves all tunnels.
        /// </summary>
        /// <returns>A collection of Tunnel entities containing all tunnels.</returns>
        public IEnumerable<Tunnel> GetAllTunnels()
        {
            return GetAllRefTunnels();
        }

        /// <summary>
        /// Retrieves a tunnel by its ID.
        /// </summary>
        /// <param name="id">The tunnel ID to retrieve.</param>
        /// <returns>A Tunnel entity containing the tunnel details.</returns>
        public Tunnel GetTunnelById(int id)
        {
            var allTunnels = GetAllRefTunnels();
            return allTunnels.Single(g => g.Id == id);
        }

        #endregion Public Methods

        #region Private Methods

        private IEnumerable<Tunnel> GetAllRefTunnels()
        {
            if (!_cacheService.Contains(CacheType.Tunnel))
            {
                var tmp = _dropZoneRepository.GetAll()
                                             .Where(d => d.Type.Contains("tunnel"))
                                             .Select(t => new Tunnel
                                             {
                                                 Id = t.Id,
                                                 Name = t.Name,
                                                 Website = t.Website,
                                                 Address = t.Address,
                                                 Email = t.Email,
                                                 Latitude = t.Latitude,
                                                 Longitude = t.Longitude
                                             });
                _cacheService.Put(CacheType.Tunnel, tmp, 5 * 60 * 1000);
            }

            return _cacheService.Get<IEnumerable<Tunnel>>(CacheType.Tunnel);
        }
        #endregion Private Methods

        #region Private Fields

        private readonly ICacheService _cacheService;
        private readonly IDropZoneService _dropZoneService;
        private readonly IDropZoneRepository _dropZoneRepository;

        #endregion Private Fields
    }
}
