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 GearService : IGearService
    {
        #region Public Constructors

        public GearService(IGearRepository gearRepository,
                           ICacheService cacheService,
                           IIdentityService identityService)
        {
            _gearRepository = gearRepository;
            _cacheService = cacheService;
            _identityService = identityService;
        }

        #endregion Public Constructors

        #region Public Methods

        public void AddNewGear(Gear newGear)
        {
            newGear.User = _identityService.ConnectedUser;
            _gearRepository.Add(newGear);

            var userId = _identityService.ConnectedUser.Id;
            _cacheService.Delete(CacheType.Gear, id: userId);
        }

        public void AddRentalGear(User newUser)
        {
            var rentalGear = new Gear
            {
                Name = "Rental gear",
                Manufacturer = "?",
                MainCanopy = "?",
                Aad = "Cypress/Vigil",
                MaxSize = 280,
                MinSize = 190,
                ReserveCanopy = "?",
                User = newUser
            };

            _gearRepository.Add(rentalGear);
        }

        public void DeleteGearById(int id)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Gear> GetAllGears()
        {
            var userId = _identityService.ConnectedUser.Id;
            if (!_cacheService.Contains(CacheType.Gear, id: userId))
                _cacheService.Put(CacheType.Gear,
                                  _gearRepository.GetAll(_identityService.ConnectedUser),
                                  5 * 60 * 1000,
                                  id: userId);

            return _cacheService.Get<IEnumerable<Gear>>(CacheType.Gear, id: userId);
        }

        public Gear GetGearById(int id)
        {
            var allGears = GetAllGears();
            return allGears.Single(g => g.Id == id);
        }

        public bool UpdateGear(int id, Gear gear)
        {
            gear.Id = id;

            return _gearRepository.Update(gear);
        }

        #endregion Public Methods

        #region Private Fields

        private readonly ICacheService _cacheService;
        private readonly IGearRepository _gearRepository;
        private readonly IIdentityService _identityService;

        #endregion Private Fields
    }
}