using AsbCloudApp.Data;
using AsbCloudApp.Data.ProcessMap;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using DocumentFormat.OpenXml.Spreadsheet;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudInfrastructure.Repository
{
#nullable enable
    public class ProcessMapRepository : CrudWellRelatedRepositoryBase<ProcessMapDto, ProcessMap>,
        IProcessMapRepository
    {
        private readonly IWellService wellService;

        public ProcessMapRepository(IAsbCloudDbContext context, IWellService wellService)
            : base(context, dbSet => 
                    dbSet.Include(x => x.Well)
                         .Include(x => x.WellSectionType)
              )
        {
            this.wellService = wellService;
        }

        public async Task<IEnumerable<ProcessMapDto>> GetAllAsync(int idWell,
            DateTime? updateFrom, CancellationToken token)
        {
            var requests = new[]
            { 
                new ProcessMapRequest { 
                    IdWell = idWell,
                    UpdateFrom = updateFrom
                }
            };

            var entities = await BuildQuery(requests)
                            .OrderBy(e => e.DepthStart)
                            .ThenBy(e => e.Id)
                            .ToListAsync(token)
                            .ConfigureAwait(false);

            var dtos = entities.Select(Convert);
            return dtos;
        }

        public async Task<IEnumerable<ProcessMapDto>> GetProcessMapAsync(IEnumerable<ProcessMapRequest> requests, CancellationToken token)
        {
            var entities = await BuildQuery(requests)
               .ToListAsync(token)
               .ConfigureAwait(false);
            var dtos = entities.Select(Convert).ToList();
            return dtos;
        }

        public override async Task<int> InsertAsync(ProcessMapDto dto,
            CancellationToken token)
        {
            dto.LastUpdate = DateTime.UtcNow;
            var result = await base.InsertAsync(dto, token);
            return result;
        }

        public override async Task<int> UpdateAsync(ProcessMapDto dto,
            CancellationToken token)
        {
            dto.LastUpdate = DateTime.UtcNow;
            var result = await base.UpdateAsync(dto, token);
            return result;
        }

        private IQueryable<ProcessMap> BuildQuery(IEnumerable<ProcessMapRequest> requests)
        {
            var query = GetQuery();
            if (requests.Any())
            {
                Expression<Func<ProcessMap, bool>> predicate = map => false;
                foreach (var request in requests)
                {
                    Expression<Func<ProcessMap, bool>> predicate2 = map => map.IdWell == request.IdWell;

                    if (request.IdWellSectionType is not null)
                        predicate2 = predicate2.And(map => map.IdWellSectionType == request.IdWellSectionType);

                    if (request.UpdateFrom is not null)
                    {
                        var timezone = wellService.GetTimezone(request.IdWell);
                        var updateFromUtc = request.UpdateFrom?.ToUtcDateTimeOffset(timezone.Hours);
                        predicate2 = predicate2.And(map => map.LastUpdate >= updateFromUtc);
                    }

                    predicate = predicate.Or(predicate2);
                }
                query = query.Where(predicate);

            }
            return query;
        }
        protected override ProcessMapDto Convert(ProcessMap entity)
        {
            var dto = entity.Adapt<ProcessMapDto>();
            dto.LastUpdate = entity.LastUpdate.ToRemoteDateTime(entity.Well.Timezone.Hours);
            dto.AxialLoad = new PlanLimitDto
            {
                LimitMax = entity.AxialLoadLimitMax,
                Plan = entity.AxialLoadPlan
            };
            dto.Flow = new PlanLimitDto
            {
                LimitMax = entity.FlowLimitMax,
                Plan = entity.FlowPlan
            };
            dto.Pressure = new PlanLimitDto
            {
                LimitMax = entity.PressureLimitMax,
                Plan = entity.PressurePlan
            };
            dto.TopDriveSpeed = new PlanLimitDto
            {
                LimitMax = entity.TopDriveSpeedLimitMax,
                Plan = entity.TopDriveSpeedPlan
            };
            dto.TopDriveTorque = new PlanLimitDto
            {
                LimitMax = entity.TopDriveTorqueLimitMax,
                Plan = entity.TopDriveTorquePlan
            };
            return dto;
        }

        protected override ProcessMap Convert(ProcessMapDto dto)
        {
            var entity = dto.Adapt<ProcessMap>();
            entity.AxialLoadPlan = dto.AxialLoad.Plan;
            entity.AxialLoadLimitMax = dto.AxialLoad.LimitMax;

            entity.FlowPlan = dto.Flow.Plan;
            entity.FlowLimitMax = dto.Flow.LimitMax;

            entity.PressurePlan = dto.Pressure.Plan;
            entity.PressureLimitMax = dto.Pressure.LimitMax;

            entity.TopDriveSpeedPlan = dto.TopDriveSpeed.Plan;
            entity.TopDriveSpeedLimitMax = dto.TopDriveSpeed.LimitMax;

            entity.TopDriveTorquePlan = dto.TopDriveTorque.Plan;
            entity.TopDriveTorqueLimitMax = dto.TopDriveTorque.LimitMax;

            return entity;
        }
    }
#nullable disable
}