"use strict";

import {
  chartExportOptions,
  createFullTitleForLineOrColumnChart,
  createCombinedTextDelimitedByComma,
  createSubtitleForChart,
  abbreviateTemperaturePhenomenonNames,
  createTooltipDateString,
} from "./chartHelpers.mjs";

/**
 * Creates an options object for each series drawn in a column chart
 * @param {Array} formattedAggregatedResultForColumnChart An array of formatted aggregated result array(s) from one or more datastreams
 * @param {Array} buildingIdsPhenomenonNamesArr An array of string(s) made up of building ID(s) + phenomenon name(s)
 * @returns {Array} An array made up of series options object(s)
 */
const createSeriesOptionsForColumnChart = function (
  formattedAggregatedResultForColumnChart,
  buildingIdsPhenomenonNamesArr
) {
  // Create an array of seriesOptions objects
  // Assumes that the observation array of arrays, phenomenon names array and phenomenon symbols array are of equal length
  // Use one of the arrays for looping
  if (
    formattedAggregatedResultForColumnChart.length !==
    buildingIdsPhenomenonNamesArr.length
  ) {
    throw new Error(
      "The observations array and phenomenon names array have different lengths"
    );
  } else {
    return formattedAggregatedResultForColumnChart.map(
      (formattedAggResArray, i) => {
        return {
          name: `${buildingIdsPhenomenonNamesArr[i]}`,
          data: formattedAggResArray,
          turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
        };
      }
    );
  }
};

/**
 * Create string for the y-axis title of a column chart
 *
 * @param {Array} phenomenonNamesArr Array of phenomenon name strings
 * @param {Array} unitOfMeasurementSymbolsArr Array of unit of measurement symbol strings
 * @returns {String} Y-axis title string for column chart
 */
const createYAxisTitleTextColumnChart = function (
  phenomenonNamesArr,
  unitOfMeasurementSymbolsArr
) {
  // The phenomenon names and unit of measurement arrays should have equal lengths
  // Use one of the arrays for looping
  if (phenomenonNamesArr.length !== unitOfMeasurementSymbolsArr.length) {
    throw new Error(
      "The phenomenon names array and unit of measurement symbols array have different lengths"
    );
  } else {
    const combinedNameSymbolArr = phenomenonNamesArr.map(
      (phenomenonName, i) =>
        `${phenomenonName} [${unitOfMeasurementSymbolsArr[i]}]`
    );

    return createCombinedTextDelimitedByComma(combinedNameSymbolArr);
  }
};

/**
 * Draw a column chart using Highcharts library
 * @param {Array} formattedObsArraysForColumnChart An array made up of formatted observation array(s) suitable for use in a column chart. The observations may either be raw or aggregated
 * @param {Object} extractedFormattedDatastreamProperties An object that contains arrays of formatted Datastream properties
 * @returns {undefined} undefined
 */
const drawColumnChartHighcharts = function (
  formattedObsArraysForColumnChart,
  extractedFormattedDatastreamProperties
) {
  // Formatted datastream properties
  let datastreamNamesArr,
    phenomenonNamesArr,
    buildingIdsPhenomenonNamesArr,
    unitOfMeasurementSymbolsArr,
    aggregationInterval,
    aggregationType;

  // Check whether the datastream properties are for aggregated observations
  // Case 1: No aggregation
  if (extractedFormattedDatastreamProperties?.aggregationType === undefined) {
    ({
      datastreamNamesArr,
      phenomenonNamesArr,
      buildingIdsPhenomenonNamesArr,
      unitOfMeasurementSymbolsArr,
    } = extractedFormattedDatastreamProperties);
  }
  // Case 2: Aggregation
  else {
    ({
      datastreamNamesArr,
      phenomenonNamesArr,
      buildingIdsPhenomenonNamesArr,
      unitOfMeasurementSymbolsArr,
      aggregationInterval,
      aggregationType,
    } = extractedFormattedDatastreamProperties);
  }

  // Create the array of series options object(s)
  const seriesOptionsArr = createSeriesOptionsForColumnChart(
    formattedObsArraysForColumnChart,
    buildingIdsPhenomenonNamesArr
  );

  const textChartTitle = createFullTitleForLineOrColumnChart(
    phenomenonNamesArr,
    aggregationInterval,
    aggregationType
  );

  const textChartSubtitle = createSubtitleForChart(datastreamNamesArr);

  const textYAxisTitle = createYAxisTitleTextColumnChart(
    abbreviateTemperaturePhenomenonNames(phenomenonNamesArr),
    unitOfMeasurementSymbolsArr
  );

  Highcharts.chart("chart-column", {
    chart: {
      type: "column",
      zoomType: "x",
    },

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

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

    xAxis: {
      type: "datetime",
      crosshair: true,
    },

    yAxis: {
      title: {
        text: textYAxisTitle,
      },
    },

    tooltip: {
      formatter() {
        // Our tooltip is shared
        // this.x -- common for all points
        // this.points -- an array containing properties for each series
        // Note that our `reduce` method is in this format:
        // ((previousValue, currentValue, currentIndex) => {...}, initialValue)
        return this.points.reduce(
          (previousValue, point, i) =>
            `${previousValue} <br/> <span style="color:${point.color}">${
              point.series.name
            }</span>: <b>${point.y.toFixed(2)} ${
              unitOfMeasurementSymbolsArr[i]
            }</b>`,
          `${createTooltipDateString(this.x, aggregationInterval)}`
        );
      },
      shared: true,
    },

    plotOptions: {
      column: {
        pointPadding: 0.2,
        borderWidth: 0,
      },
    },

    exporting: chartExportOptions,

    series: seriesOptionsArr,
  });
};

export { drawColumnChartHighcharts };
