using System.Collections.Generic;
using System.Linq;
using Kreta.BusinessLogic.HelperClasses;
using Kreta.Core.Elearning.Nexius;
using Kreta.Framework.Caching;
using Nexius.IdentityProvider.Model.External.V1;

namespace Kreta.KretaServer.Caching
{
    public class ElearningCache : GenericCache<IDictionary<string, KretaCourseCo>>
    {
        private static readonly string ElearningCacheKey = $"{nameof(Kreta)}_{nameof(ElearningCache)}";

        public ElearningCache(Framework.Caching.CacheManager cacheManager) : base(cacheManager, nameof(ElearningCache))
        {
        }

        public IDictionary<string, Course> GetCourses(IEnumerable<string> idList, INexiusCourseService nexiusCourseService)
        {
            var allCourses = GetAllCourses(nexiusCourseService);
            var result = new Dictionary<string, Course>();
            foreach (var id in idList)
            {
                if (allCourses.TryGetValue(id.ToLower(), out KretaCourseCo co))
                {
                    result.Add(id.ToLower(), co.ToCourse());
                }
            }

            return result;
        }

        private IDictionary<string, KretaCourseCo> GetAllCourses(INexiusCourseService nexiusCourseService)
        {
            return Get(ElearningCacheKey) ?? LoadAllCourses(nexiusCourseService);
        }

        private IDictionary<string, KretaCourseCo> LoadAllCourses(INexiusCourseService nexiusCourseService)
        {
            var courseDictionary = nexiusCourseService.GetAllCourses().ToDictionary(c => c.Id.ToString().ToLower(), c => new KretaCourseCo(c));
            AddOrUpdate(ElearningCacheKey, courseDictionary, x => courseDictionary);

            return courseDictionary;
        }
    }
}