"use strict";

import {
  chartExportOptions,
  extractSamplingRateFromDatastreamName,
} from "./chartHelpers.mjs";

/**
 * Format the response from SensorThings API to make it suitable for use in a line chart
 * @param {Array} obsArray Array of observations (timestamp + value) that is response from SensorThings API
 * @returns {Array} Array of formatted observations suitable for use in a line chart
 */
const formatSensorThingsApiResponseForLineChart = function (obsArray) {
  if (!obsArray) return;

  return obsArray.map((result) => {
    const timestampObs = new Date(result[0].slice(0, -1)).getTime(); // slice() removes trailing "Z" character in timestamp
    const valueObs = result[1];
    return [timestampObs, valueObs];
  });
};

/**
 * Concatenates metadata properties to create a string for either the title or subtitle of a line chart
 * @param {Array} phenomenonNamesArr An array of phenomenon name strings
 * @returns {String} A string made up of combined phenomenon names
 */
const createCombinedTextForLineChartTitles = function (phenomenonNamesArr) {
  return phenomenonNamesArr.join(", ");
};

/**
 * Creates an options object for each series drawn in the line chart
 * @param {Array} formattedObsArraysForLineChart An array of formatted observation array(s) from one or more datastreams
 * @param {Array} phenomenonNamesArr An array of phenomenon name(s)
 * @returns {Array} An array made up of series options object(s)
 */
const createSeriesOptionsForLineChart = function (
  formattedObsArraysForLineChart,
  phenomenonNamesArr
) {
  // An array of colors, in hexadecimal format, provided by the global Highcharts object
  const seriesColors = Highcharts.getOptions().colors;

  // Create a copy of the colors array
  const seriesColorsArr = [...seriesColors];

  // Create an array of seriesOptions objects
  // Assumes that the observation array of arrays and phenomenon names array are of equal length
  // Use one of the arrays for looping
  if (formattedObsArraysForLineChart.length !== phenomenonNamesArr.length)
    throw new Error(
      "The observations array and phenomenon names array have different lengths"
    );

  return formattedObsArraysForLineChart.map((formattedObsArray, i) => {
    return {
      name: `${phenomenonNamesArr[i]}`,
      data: formattedObsArray,
      color: seriesColorsArr[i],
      turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
    };
  });
};

/**
 * Draw a line chart using Highcharts library
 * @param {Array} formattedObsArraysForLineChart An array made up of formatted observation array(s) suitable for use in a line chart
 * @param {Object} extractedFormattedDatastreamPropertiesArr An object that contains arrays of formatted Datastream properties
 * @returns {undefined} undefined
 */
const drawLineChartHighcharts = function (
  formattedObsArraysForLineChart,
  extractedFormattedDatastreamProperties
) {
  // Arrays of datastream properties
  const {
    datastreamNamesArr,
    phenomenonNamesArr,
    unitOfMeasurementSymbolsArr,
  } = extractedFormattedDatastreamProperties;

  // Chart title and subtitle text
  const textChartTitle =
    createCombinedTextForLineChartTitles(phenomenonNamesArr);

  const textChartSubtitle = `Sampling rate(s): ${createCombinedTextForLineChartTitles(
    extractSamplingRateFromDatastreamName(datastreamNamesArr)
  )}`;

  // Create the array of series options object(s)
  const seriesOptionsArr = createSeriesOptionsForLineChart(
    formattedObsArraysForLineChart,
    phenomenonNamesArr,
    unitOfMeasurementSymbolsArr
  );

  Highcharts.stockChart("chart-line", {
    chart: {
      zoomType: "x",
    },

    rangeSelector: {
      selected: 5,
    },

    title: {
      text: textChartTitle,
      "align": "left",
    },

    subtitle: {
      text: textChartSubtitle,
      align: "left",
    },

    tooltip: {
      formatter() {
        // Our tooltip is split
        // this.x -- common for all points
        // this.points -- an array containing properties for each series
        return [`${Highcharts.dateFormat("%A, %b %e, %Y", this.x)}`].concat(
          this.points
            ? this.points.map(
                (point, i) =>
                  `<span style="color:${point.color}">${
                    point.series.name
                  }</span>: <b>${point.y.toFixed(2)} ${
                    unitOfMeasurementSymbolsArr[i]
                  }</b>`
              )
            : []
        );
      },
    },

    exporting: chartExportOptions,

    series: seriesOptionsArr,
  });
};

export { formatSensorThingsApiResponseForLineChart, drawLineChartHighcharts };
