using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Pumps;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;

namespace adas_core.Application.Customizations.HGM;

//Custom for Hospital Gregorio Marañón
/// <summary>
/// Represents a collection of calculated observations, providing a concrete implementation of the <see cref="ICalculatedObservations"/> contract.
/// </summary>
public class CalculatedObservations : ICalculatedObservations
{
    private readonly List<string> _highFrequencyVentilation = [];
    private readonly List<string> _invasiveVentilation = [];
    private readonly ILogger<CalculatedObservations> _logger;
    private readonly List<string> _nonInvasiveVentilation = [];
    private readonly Lazy<IObservationService> _observationService;

    public CalculatedObservations(IServiceProvider serviceProvider)
    {
        var apiSettings = serviceProvider.GetRequiredService<IOptions<ApiSettings>>().Value;
        _logger = serviceProvider.GetRequiredService<ILogger<CalculatedObservations>>();
        _observationService = serviceProvider.GetRequiredService<Lazy<IObservationService>>();

        var highFrequencyVentilation = apiSettings.HighFrequencyVentilation ?? null;
        highFrequencyVentilation?.ForEach(x => _highFrequencyVentilation.Add(x.Trim()));

        var invasiveVentilation = apiSettings.InvasiveVentilation ?? null;
        invasiveVentilation?.ForEach(x => _invasiveVentilation.Add(x.Trim()));

        var nonInvasiveVentilation = apiSettings.NonInvasiveVentilation ?? null;
        nonInvasiveVentilation?.ForEach(x => _nonInvasiveVentilation.Add(x.Trim()));
    }

    /// <summary>
    /// Maps a patient observation by applying domain-specific transformations based on the observation name.
    /// Handles the "Resp_Mode" case by calculating the ventilation mode, while observations with a null or empty name are returned unchanged.
    /// </summary>
    /// <param name="obs">The patient observation to be mapped.</param>
    /// <param name="onlyByName">Flag indicating whether the mapping should be restricted to name-based criteria.</param>
    /// <returns>The mapped patient observation, or the original observation if no applicable mapping is found.</returns>
    public async Task<T?> Map<T>(T obs, bool onlyByName = false) where T : BasePatientObservation
    {
        if (string.IsNullOrEmpty(obs.Name)) return obs;

        switch (obs.Name)
        {
            case "Resp_Mode":
                await CalculateVentilationMode(obs);
                break;
        }

        return obs;
    }


    /// <summary>
    /// Asynchronously maps the specified <paramref name="treatment"/> to a <see cref="PatientTreatment"/> result.
    /// </summary>
    /// <param name="treatment">The <see cref="PatientTreatment"/> instance to be mapped.</param>
    /// <returns>A task that represents the asynchronous mapping operation, containing the resulting <see cref="PatientTreatment"/>.</returns>
    /// <exception cref="System.NotImplementedException">Thrown to indicate that the method has not yet been implemented.</exception>
    public Task<PatientTreatment> Map(PatientTreatment treatment)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Maps the provided patient diagnosis to the target representation asynchronously.
    /// </summary>
    /// <param name="diagnosis">The patient diagnosis to be mapped.</param>
    /// <returns>A task that represents the asynchronous mapping operation, containing the mapped <see cref="PatientDiagnosis"/>.</returns>
    /// <exception cref="NotImplementedException">Thrown when the method is invoked, as the mapping logic has not been implemented yet.</exception>
    public Task<PatientDiagnosis> Map(PatientDiagnosis diagnosis)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Maps the provided <see cref="PumpObservation"/> by returning it unchanged, wrapped in a completed task.
    /// </summary>
    /// <param name="pumpObservation">The pump observation to map.</param>
    /// <returns>A completed task containing the provided <see cref="PumpObservation"/>.</returns>
    public async Task<PumpObservation> Map(PumpObservation pumpObservation)
    {
        return await Task.FromResult(pumpObservation);
    }


    /// <summary>
    /// Asynchronously calculates the active bolus for the specified patient.
    /// </summary>
    /// <param name="patientId">The unique identifier of the patient for whom the active bolus is calculated.</param>
    /// <exception cref="NotImplementedException">The method is not yet implemented.</exception>
    public Task CalculateActiveBolus(ObjectId patientId)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Calculates the medicine observation for a patient based on the provided active medicines.
    /// </summary>
    /// <param name="activeMedicines">The list of active medicines currently associated with the patient.</param>
    /// <param name="patientId">The unique identifier of the patient for whom the observation is being calculated.</param>
    /// <exception cref="NotImplementedException">The method is not yet implemented.</exception>
    public Task CalculateMedicineObservation(List<Medicine> activeMedicines, ObjectId patientId)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Resolves time inconsistencies between the specified <paramref name="newObservation"/> and the last recorded patient observation, returning a corrected observation when applicable.
    /// </summary>
    /// <param name="newObservation">The new patient observation to reconcile against the last recorded observation.</param>
    /// <returns>A task that returns the corrected <see cref="PatientObservation"/>, or <c>null</c> when no last observation is available to compare against.</returns>
    /// <exception cref="System.NotImplementedException">The method is not yet implemented.</exception>
    public Task<PatientObservation?> FixTimeInconsistencyWithLast(PatientObservation newObservation)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Retrieves the active treatments currently associated with the specified patient.
    /// </summary>
    /// <param name="id">The identifier of the patient whose active treatments are being requested.</param>
    /// <returns>A task that yields a collection of active <see cref="PatientTreatment"/> entries for the patient.</returns>
    /// <exception cref="NotImplementedException">Thrown because the method has not been implemented yet.</exception>
    public Task<IEnumerable<PatientTreatment?>> GetActiveTreatmentsByPatient(ObjectId id)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Pre-maps the provided list of patient observations before further processing, returning the list as-is in a completed task.
    /// </summary>
    /// <param name="listToInsert">The list of patient observations to be pre-mapped.</param>
    /// <returns>A completed task containing the provided list of patient observations.</returns>
    public Task<List<PatientObservation>> PreMapList(List<PatientObservation> listToInsert)
    {
        return Task.FromResult(listToInsert);
    }

    /// <summary>
    /// Maps a source alarm to a patient observation, returning the provided observation as the result.
    /// </summary>
    /// <param name="obs">The patient observation to return as the mapped result.</param>
    /// <param name="alarmToInsert">The patient observation alarm to be considered during mapping.</param>
    /// <returns>A <see cref="Task{PatientObservation}"/> containing the provided <paramref name="obs"/>.</returns>
    public Task<PatientObservation> MapSourceAlarm(PatientObservation obs, PatientObservationAlarm alarmToInsert)
    {
        return Task.FromResult(obs);
    }

    /// <summary>
    /// Sends an alarm for the specified patient observation.
    /// </summary>
    /// <param name="obs">The patient observation that triggers the alarm.</param>
    /// <param name="name">The name associated with the alarm.</param>
    /// <param name="code">The optional alarm code identifying the alarm type.</param>
    /// <returns>A task that represents the asynchronous alarm sending operation.</returns>
    /// <exception cref="NotImplementedException">Thrown when the method is invoked, as it is not yet implemented.</exception>
    public Task SendAlarm(PatientObservation obs, string name, AlarmEnum.Name? code)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Calculates and persists the ventilation mode (<c>Resp_Type</c>) for a patient observation by mapping the observed value against known high-frequency, invasive, and non-invasive ventilation vocabularies, defaulting to <c>None</c> when the value is empty or unrecognized.
    /// </summary>
    /// <param name="obs">The base patient observation whose value is used to derive the respiration type; it is cast to <see cref="PatientObservation"/> to access the value.</param>
    private async Task CalculateVentilationMode(BasePatientObservation obs)
    {
        var pobs = (PatientObservation)obs;
        var respTypeObs = new PatientObservation
        {
            Name = "Resp_Type",
            CodingSystem = "ADAS",
            PatientId = obs.PatientId,
            Time = obs.Time
        };

        var strValue = pobs.Value.ToString();
        if (string.IsNullOrEmpty(strValue))
            respTypeObs.Value = nameof(RespirationType.None);
        else
            respTypeObs.Value = _highFrequencyVentilation.Contains(strValue)
                ? nameof(RespirationType.HighFrequencyVentilation)
                : _invasiveVentilation.Contains(strValue)
                    ? respTypeObs.Value = nameof(RespirationType.Invasive)
                    : _nonInvasiveVentilation.Contains(strValue)
                        ? respTypeObs.Value = nameof(RespirationType.NonInvasive)
                        : nameof(RespirationType.None);


        var wasInserted = await _observationService.Value.InsertIfChanged("Resp_Type", respTypeObs);
        if (wasInserted)
            _logger.LogDebug("Calculated Resp_Type for patientid: {respTypeObsPatientid} value: {respType}",
                respTypeObs.PatientId, respTypeObs.Value);
    }
}