using AutoMapper;
using PARR.API.Contracts.V1.Responses;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Domain.Entities.Job;
using PARR.Domain.Settings;

namespace PARR.API.MappingProfiles.Resolvers
{
    public class JobGroupScheduleResolver : IValueResolver<JobGroup, JobGroupResponse, JobGroupScheduleResponse?>
    {
        private readonly IEsppSchTypeConfigRepository esppConfigService;
        private readonly ILogger<JobGroupScheduleResolver> logger;
        private readonly IMapper mapper;
        private readonly SettingsFromDb settingsFromDb;
        private readonly IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService;

        public JobGroupScheduleResolver(
            IEsppSchTypeConfigRepository esppConfigService,
            ILogger<JobGroupScheduleResolver> logger,
            IMapper mapper,
            SettingsFromDb settingsFromDb,
            IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService
            )
        {
            this.esppConfigService = esppConfigService;
            this.logger = logger;
            this.mapper = mapper;
            this.settingsFromDb = settingsFromDb;
            this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
        }


        public JobGroupScheduleResponse? Resolve(JobGroup source, JobGroupResponse destination, JobGroupScheduleResponse? destMember, ResolutionContext context)
        {
            var schedule = esppConfigService.GetEsppScheduleDto(source.Id);

            if (schedule == null)
            {
                logger.LogError($"Не смог замапить расписание, так как оно null. JobGroupId: {source.Id}");
                return null;
            }

            var response = new JobGroupScheduleResponse
            {
                //Timezone = settingsFromDb.ScheduleTimezone,
                Timezone = scheduleResponseAreaTimeOffsetService.GetDefault.EsppValue,
                TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
                Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
            };

            return response;
        }
    }
}
