using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudInfrastructure.Services
{
    public class DrillFlowChartService : CrudServiceBase<DrillFlowChartDto, DrillFlowChart>,
        IDrillFlowChartService
    {
        private readonly IAsbCloudDbContext db;
        private readonly IWellService wellService;

        public DrillFlowChartService(IAsbCloudDbContext context, IWellService wellService)
            : base(context)
        {
            this.db = context;
            this.wellService = wellService;
        }

        public async Task<IEnumerable<DrillFlowChartDto>> GetAllAsync(int idWell,
            DateTime updateFrom, CancellationToken token = default)
        {
            var timezone = wellService.GetTimezone(idWell);
            var updateFromUtc = updateFrom.ToUtcDateTimeOffset(timezone.Hours);
            var entities = await (from p in db.DrillFlowChart
                                  where p.IdWell == idWell &&
                                        p.LastUpdate > updateFromUtc
                                  orderby p.DepthStart, p.Id
                                  select p)
                             .ToListAsync(token)
                             .ConfigureAwait(false);

            var dtos = entities.Select(entity =>
            {
                var dto = entity.Adapt<DrillFlowChartDto>();
                dto.LastUpdate = entity.LastUpdate.ToRemoteDateTime(timezone.Hours);
                return dto;
            });
            return dtos;
        }

        public async Task<int> InsertAsync(int idWell, DrillFlowChartDto dto,
            CancellationToken token = default)
        {
            dto.IdWell = idWell;
            dto.LastUpdate = DateTime.UtcNow;
            var result = await base.InsertAsync(dto, token).ConfigureAwait(false);
            return result;
        }

        public async Task<int> InsertRangeAsync(int idWell, IEnumerable<DrillFlowChartDto> dtos,
            CancellationToken token = default)
        {
            foreach (var dto in dtos)
            {
                dto.IdWell = idWell;
                dto.LastUpdate = DateTime.UtcNow;
            }

            var result = await base.InsertRangeAsync(dtos, token).ConfigureAwait(false);

            return result;
        }

        public async Task<int> UpdateAsync(int idWell, int idDto, DrillFlowChartDto dto,
            CancellationToken token = default)
        {
            dto.IdWell = idWell;
            dto.LastUpdate = DateTime.UtcNow;

            var result = await base.UpdateAsync(idDto, dto, token).ConfigureAwait(false);
            return result;
        }
    }
}