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

namespace AsbCloudInfrastructure.Repository
{
    internal class TrajectoryFactRepository : ITrajectoryFactRepository
    {
        private readonly IAsbCloudDbContext db;
        private readonly IWellService wellService;
        public TrajectoryFactRepository(IAsbCloudDbContext db, IWellService wellService)
        {
            this.db = db;
            this.wellService = wellService;
        }
        
        public async Task<IEnumerable<TrajectoryGeoFactDto>> GetAsync(int idWell, CancellationToken token)
        {
            var well = await wellService.GetOrDefaultAsync(idWell,
                token);
            
            if (well is null)
                return Enumerable.Empty<TrajectoryGeoFactDto>();

            var entities = await db.Record7
                .AsNoTracking()
                .Where(x => x.IdTelemetry == well.IdTelemetry)
                .Where(coord => coord.Deptsvym != null && coord.Svyinc != null && coord.Svyazc != null)
                .OrderBy(e => e.Deptsvym)
                .ToArrayAsync(token);

            var result = entities
                .Select(coord => new TrajectoryGeoFactDto
                {
                    IdWell = idWell,
                    AzimuthMagnetic = coord.Svymtf,
                    VerticalDepth = coord.Deptsvyv,
                    NorthOrifice = coord.Svyns,
                    EastOrifice = coord.Svyew,
                    WellboreDepth = coord.Deptsvym!.Value,
                    ZenithAngle = coord.Svyinc!.Value,
                    AzimuthGeo = coord.Svyazc!.Value
                })
                .ToArray();

            return result;
        }
    }
}