using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.DAL.Context;
using PARR.Domain.Entities.Schedule;
using PARR.Domain.Settings;

namespace PARR.DAL.Repositories.Schedule
{
    internal sealed class ScheduleResponseAreaTimeOffsetRepository : IScheduleResponseAreaTimeOffsetRepository
    {
        private readonly IReadOnlyDictionary<string, ScheduleResponseAreaTimeOffset> offsetList;
        
        /// <summary>
        /// ЗО по умолчанию
        /// </summary>
        private readonly string defaultResponseArea;

        /// <summary>
        /// Настройки, если не нашли в offsetList
        /// </summary>
        private readonly ScheduleResponseAreaTimeOffset defaultOffset;
        private readonly ILogger<ScheduleResponseAreaTimeOffsetRepository> logger;

        public ScheduleResponseAreaTimeOffsetRepository(DataContext dataContext, SettingsFromDb settingsFromDb, ILogger<ScheduleResponseAreaTimeOffsetRepository> logger)
        {
            offsetList = dataContext.ScheduleResponseAreaTimeOffsets
                .AsNoTracking()
                .ToDictionary(t => t.ResponseArea, t => t, StringComparer.OrdinalIgnoreCase);

            if (string.IsNullOrEmpty(settingsFromDb.DefaultResponseAreaToTimeOffset))
                defaultResponseArea = "17-МСК";
            else
                defaultResponseArea = settingsFromDb.DefaultResponseAreaToTimeOffset;


            defaultOffset = new ScheduleResponseAreaTimeOffset
            {
                ResponseArea = "17-МСК",
                EsppValue = "",
                UtcTimeOffset = new TimeSpan(3, 0, 0)
            };
            this.logger = logger;
        }


        public IReadOnlyDictionary<string, ScheduleResponseAreaTimeOffset> GetAll => offsetList;

        public ScheduleResponseAreaTimeOffset GetDefault => GetByResponseAreaOrDefault(defaultResponseArea);

        public ScheduleResponseAreaTimeOffset GetByResponseAreaOrDefault(string responseArea)
        {
            offsetList.TryGetValue(responseArea, out var value);

            if (value != null)
            {
                logger.LogDebug("Получил часовой пояс по ЗО '{responseArea}', esppValue: {EsppValue}, utcTimeOffset: {utcTimeOffset}", responseArea, value.EsppValue, value.UtcTimeOffset);
                return value;
            }
            else
            {
                logger.LogWarning("Не смог получить часовой пояс по ЗО '{responseArea}', вернул часово пояс по умолчанию: name: {name}, esppValue: {EsppValue}, utcTimeOffset: {utcTimeOffset}",
                                        responseArea, defaultOffset.ResponseArea, defaultOffset.EsppValue, defaultOffset.UtcTimeOffset);
                return defaultOffset;
            }
            //return offsetList.TryGetValue(responseArea, out var value) ? value : defaultOffset;
        }


        //public IQueryable<ScheduleResponseAreaTimeOffset> Get()
        //{
        //    return dataContext.ScheduleResponseAreaTimeOffsets;
        //}

        //public async Task<string?> GetTimeOffsetByResponseAreaAsync(string responseArea)
        //{
        //    var result = await dataContext.ScheduleResponseAreaTimeOffsets.FirstOrDefaultAsync(t => t.ResponseArea == responseArea);

        //    return result != null ? result.TimeOffset : null;
        //}
    }
}
