"use strict";

import { getMetadataPlusObservationsFromSingleOrMultipleDatastreams } from "./fetchData.mjs";

import { extractPhenomenonNameFromDatastreamName } from "./fetchedDataProcessing.mjs";

/**
 * Calculate the temperature difference, dT, between Vorlauf temperature [VL] and Rücklauf temperature [RL] (i.e., dT = VL - RL)
 * @param {String} baseUrl Base URL of the STA server
 * @param {Object} urlParams The URL parameters to be sent together with the GET request
 * @param {String} buildingId The building ID as a string
 * @param {String} samplingRate The sampling rate as a string
 * @returns {Promise} A promise that contains an array (that is made up of a temperature difference array and a metadata object) when fulfilled
 */
export const calculateVorlaufMinusRuecklaufTemperature = async function (
  baseUrl,
  urlParams,
  buildingId,
  samplingRate
) {
  try {
    const bldgSensorSamplingRateNestedArr = [
      [buildingId, "vl", samplingRate],
      [buildingId, "rl", samplingRate],
    ];

    const BUILDING_ID = buildingId;
    const SAMPLING_RATE = samplingRate;

    const observationsPlusMetadata =
      await getMetadataPlusObservationsFromSingleOrMultipleDatastreams(
        baseUrl,
        urlParams,
        bldgSensorSamplingRateNestedArr
      );

    // Extract Vorlauf temperature, Ruecklauf temperature and metadata
    const [
      [vorlaufTemperatureObsArr, ruecklaufTemperatureObsArr],
      [metadataVorlauf, metadataRuecklauf],
    ] = observationsPlusMetadata;

    // Extract the temperature values
    const vorlaufTemperatureValues = vorlaufTemperatureObsArr.map(
      (vlTempObs) => vlTempObs[1]
    );
    const ruecklaufTemperatureValues = ruecklaufTemperatureObsArr.map(
      (rlTempObs) => rlTempObs[1]
    );

    // The arrays have equal length, we need only use one of them for looping
    // Resulting array contains the following pairs (timestamp + dT)
    const vorlaufMinusRuecklaufTemperatureObs = vorlaufTemperatureObsArr.map(
      (vlTempObs, i) => [
        vlTempObs[0], // timestamp
        vorlaufTemperatureValues[i] - ruecklaufTemperatureValues[i],
      ]
    );

    // From Vorlauf metadata, extract `name` and `unitOfMeasurement`
    const {
      name: datastreamNameVorlauf,
      unitOfMeasurement: unitOfMeasurementVorlauf,
    } = metadataVorlauf;

    // From Ruecklauf metadata, extract `name`
    const { name: datastreamNameRuecklauf } = metadataRuecklauf;

    // Extract the phenomenon names from the Datastream names
    const phenomenonNameVorlauf = extractPhenomenonNameFromDatastreamName(
      datastreamNameVorlauf
    );
    const phenomenonNameRuecklauf = extractPhenomenonNameFromDatastreamName(
      datastreamNameRuecklauf
    );

    // Create our custom datastream description text
    // The resulting datastream description string has two `temperature` substrings;
    // replace the first occurence with an empty string
    const descriptionTempDifference =
      `Computed dT: ${phenomenonNameVorlauf} minus ${phenomenonNameRuecklauf}`.replace(
        "temperature",
        ""
      );

    // Create our custom datastream name text
    const nameTempDifference = `BOSCH_${BUILDING_ID} / dT Temperature difference (VL-RL) DS:${SAMPLING_RATE}`;

    // The datastream object that we return needs to have these property names
    const description = descriptionTempDifference;
    const name = nameTempDifference;
    const unitOfMeasurement = unitOfMeasurementVorlauf;

    return [
      vorlaufMinusRuecklaufTemperatureObs,
      {
        description,
        name,
        unitOfMeasurement,
      },
    ];
  } catch (err) {
    console.error(err);
  }
};
