using adas_core.Application.Services.Interfaces; using adas_core.Domain.Enums; using adas_core.Domain.Models; using adas_core.Domain.Models.Pumps; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MongoDB.Bson; namespace adas_core.Application.Customizations.BD; /// /// Represents a service that provides calculated observations, implementing the interface. /// /// /// This type is instantiated with a primary constructor that accepts an to resolve its dependencies. /// /// public class CalculatedObservations(IServiceProvider serviceProvider) : ICalculatedObservations { private readonly ILogger _logger = serviceProvider.GetRequiredService>(); private readonly Lazy _observationService = serviceProvider.GetRequiredService>(); /// /// Maps the specified patient observation by returning it unchanged within a completed task. /// The parameter is accepted to indicate whether the mapping should match observations by name only. /// /// The patient observation to map. /// Indicates whether the mapping should match observations by name only. /// A containing the provided observation. /// public Task Map(T obs, bool onlyByName = false) where T : BasePatientObservation { return Task.FromResult(obs)!; } /// /// Returns the provided as a completed task without modification. /// /// The patient treatment instance to map. /// A completed containing the provided treatment. /// public Task Map(PatientTreatment treatment) { return Task.FromResult(treatment); } /// /// Maps the provided instance to a completed , returning the same diagnosis unchanged. /// /// The instance to map. /// A containing the provided . /// public Task Map(PatientDiagnosis diagnosis) { return Task.FromResult(diagnosis); } /// /// Maps a pump observation, creating an associated alarm observation when the observation code is "IHE PCD-04". /// /// The pump observation to be mapped. /// The mapped pump observation. /// public async Task Map(PumpObservation pumpObservation) { if (pumpObservation.Code == "IHE PCD-04") await CreatePumpAlarmObservation(pumpObservation); return pumpObservation; } /// /// Calculates medicine observations for the specified patient using the provided list of active medicines. /// /// The list of active medicines associated with the patient. /// The unique identifier of the patient for whom the observations are calculated. /// public Task CalculateMedicineObservation(List activeMedicines, ObjectId patientId) { return Task.CompletedTask; } /// /// Asynchronously calculates the active bolus for the specified patient. /// /// The unique identifier of the patient whose active bolus is being calculated. /// A task that represents the asynchronous calculation of the active bolus. /// public Task CalculateActiveBolus(ObjectId patientId) { return Task.CompletedTask; } /// /// Retrieves the collection of active treatments associated with the specified patient identifier. /// /// The unique identifier of the patient whose active treatments are being requested. /// A task that represents the asynchronous operation, containing an of nullable entries for the patient's active treatments. /// Thrown to indicate that the method is not yet implemented. /// public Task> GetActiveTreatmentsByPatient(ObjectId id) { throw new NotImplementedException(); } /// /// Resolves time inconsistencies between the provided new patient observation and the previously recorded one, returning a corrected observation when applicable. /// /// The new patient observation to be reconciled against the last stored observation. /// A task that yields the time-corrected , or null when no correction is required or no prior observation exists. /// Thrown because the method has not been implemented yet. /// public Task FixTimeInconsistencyWithLast(PatientObservation newObservation) { throw new NotImplementedException(); } /// /// Performs a pre-mapping operation on the list of patient observations before further processing. /// In the base implementation, the list is returned unchanged, serving as a pass-through that may be overridden to apply custom transformations or validations. /// /// The list of patient observations to be pre-mapped before insertion. /// A task containing the provided list of patient observations. /// public Task> PreMapList(List listToInsert) { return Task.FromResult(listToInsert); } /// /// Maps a source onto an existing , producing an updated observation that incorporates the alarm data. /// /// The existing patient observation to which the alarm will be mapped. /// The source alarm to be inserted/mapped into the observation. /// A that represents the asynchronous mapping operation, returning the resulting patient observation. /// Thrown because the method has not been implemented yet. /// public Task MapSourceAlarm(PatientObservation obs, PatientObservationAlarm alarmToInsert) { throw new NotImplementedException(); } /// /// Sends an alarm notification based on a patient observation, associated name, and optional alarm code. /// /// The patient observation that triggers the alarm. /// The name associated with the alarm. /// The optional alarm code that categorizes the alarm; may be null. /// A task that represents the asynchronous alarm sending operation. /// Thrown because the method is not yet implemented. /// public Task SendAlarm(PatientObservation obs, string name, AlarmEnum.Name? code) { throw new NotImplementedException(); } /// /// Creates and inserts a patient observation representing a pump alarm event. /// The observation value is populated with the device identifier when available, otherwise the infusion identifier, /// and the patient identifier is only assigned if present on the source pump observation. /// Any exception raised while inserting the observation is logged and swallowed rather than rethrown. /// /// The pump observation containing the alarm state, type, timestamps, and identifiers used to build the alarm patient observation. /// A completed representing the insert operation, which never faults since exceptions are caught internally. /// private Task CreatePumpAlarmObservation(PumpObservation pumpObservation) { PatientObservation patientObservationAlarm = new() { CodingSystem = "ADAS_ALARM", Code = pumpObservation.AlarmState, Name = $"Alarm_Pump_{pumpObservation.AlarmType}", Value = pumpObservation.DeviceId != null ? $"Device Id: {pumpObservation.DeviceId}" : $"Infusion Id {pumpObservation.InfusionId}", Time = pumpObservation.Time }; if (pumpObservation.PatientId.HasValue) patientObservationAlarm.PatientId = pumpObservation.PatientId.Value; //CheckAlarmConfig(patientObservationAlarm); try { _ = _observationService.Value.InsertObservation(patientObservationAlarm, mapObs: false); } catch (Exception e) { _logger.LogError("Error inserting Pump Observation Alarm. Exception: {e}", e); } return Task.CompletedTask; } }