<!--
 Open MCT, Copyright (c) 2014-2024, United States Government
 as represented by the Administrator of the National Aeronautics and Space
 Administration. All rights reserved.

 Open MCT is licensed under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0.

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 License for the specific language governing permissions and limitations
 under the License.

 Open MCT includes source code licensed under additional open source
 licenses. See the Open Source Licenses file (LICENSES.md) included with
 this source code distribution or the Licensing information page available
 at runtime from the About dialog for additional information.
-->
<template>
  <div ref="plotWrapper" class="has-local-controls" :class="{ 's-unsynced': isZoomed }">
    <div v-if="isZoomed" class="l-state-indicators">
      <span
        class="l-state-indicators__alert-no-lad t-object-alert t-alert-unsynced icon-alert-triangle"
        title="This plot is not currently displaying the latest data. Reset pan/zoom to view latest data."
      ></span>
    </div>
    <div ref="plot" class="c-scatter-chart"></div>
    <div
      ref="localControl"
      class="gl-plot__local-controls h-local-controls h-local-controls--overlay-content c-local-controls--show-on-hover"
    >
      <button
        v-if="data.length"
        class="c-button icon-reset"
        :disabled="!isZoomed"
        title="Reset pan/zoom"
        @click="reset()"
      ></button>
    </div>
  </div>
</template>
<script>
import Plotly from 'plotly-basic';

const MULTI_AXES_X_PADDING_PERCENT = {
  LEFT: 8,
  RIGHT: 94
};

import { getValidatedData } from '@/plugins/plan/util';

const PATH_COLORS = ['blue', 'red', 'green'];
const MARKER_COLOR = 'white';

export default {
  inject: ['openmct', 'domainObject'],
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    plotAxisTitle: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  emits: ['subscribe', 'unsubscribe'],
  data() {
    return {
      isZoomed: false,
      yAxisRange: {
        min: '',
        max: ''
      },
      xAxisRange: {
        min: '',
        max: ''
      }
    };
  },
  watch: {
    data: {
      immediate: false,
      handler() {
        this.updateData();
      },
      deep: true
    }
  },
  mounted() {
    this.getUnderlayPlotData();

    Plotly.newPlot(
      this.$refs.plot,
      Array.from(this.data.concat(this.getShapes(this.shapesData))),
      this.getLayout(),
      {
        responsive: true,
        displayModeBar: false
      }
    );
    this.registerListeners();

    this.$refs.plot.on('plotly_relayout', this.zoom);
  },
  beforeUnmount() {
    if (this.$refs.plot && this.$refs.plot.off) {
      this.$refs.plot.off('plotly_relayout', this.zoom);
    }

    if (this.plotResizeObserver) {
      this.plotResizeObserver.disconnect();
      clearTimeout(this.resizeTimer);
    }

    if (this.unlistenUnderlay) {
      this.unlistenUnderlay();
    }

    if (this.unlistenUnderlayRanges) {
      this.unlistenUnderlayRanges();
    }

    if (this.unobserveColorChanges) {
      this.unobserveColorChanges();
    }

    Plotly.purge(this.$refs.plot);
  },
  methods: {
    getUnderlayPlotData() {
      if (this.domainObject.selectFile) {
        this.shapesData = getValidatedData(this.domainObject);
      } else {
        this.shapesData = [];
      }
    },
    observeForUnderlayPlotChanges() {
      this.getUnderlayPlotData();
      this.updateData();
    },
    getAxisMinMax() {
      if (!this.data.length) {
        return;
      }

      // For now, use x and y axes min, max values only if an underlay is available
      if (this.shapesData.length && this.data[0].xaxis) {
        this.xAxisRange = this.data[0].xaxis;
      }

      if (this.shapesData.length && this.data[0].yaxis) {
        this.yAxisRange = this.data[0].yaxis;
      }
    },
    getLayout() {
      this.getAxisMinMax();

      const yAxesMeta = this.getYAxisMeta();
      const primaryYaxis = this.getYaxisLayout(yAxesMeta['1']);
      const xAxisDomain = this.getXAxisDomain(yAxesMeta);

      const shapes = this.shapesData.map((shapeData, index) => {
        if (
          !shapeData.x ||
          !shapeData.y ||
          !shapeData.x.length ||
          !shapeData.y.length ||
          shapeData.x.length !== shapeData.y.length
        ) {
          return '';
        }

        let path = `M ${shapeData.x[0]},${shapeData.y[0]}`;
        shapeData.x.forEach((point, shapeIndex) => {
          if (shapeIndex > 0) {
            path = `${path} L${point},${shapeData.y[shapeIndex]}`;
          }
        });

        return {
          path,
          type: 'path',
          line: {
            color: PATH_COLORS[index]
          },
          opacity: 0.5
        };
      });

      return {
        autosize: true,
        showlegend: false,
        textposition: 'auto',
        font: {
          family: 'Helvetica Neue, Helvetica, Arial, sans-serif',
          size: '12px',
          color: '#666'
        },
        xaxis: {
          domain: xAxisDomain,
          range: [this.xAxisRange.min, this.xAxisRange.max],
          title: this.plotAxisTitle.xAxisTitle,
          automargin: true
        },
        yaxis: primaryYaxis,
        margin: {
          l: 5,
          r: 5,
          t: 5,
          b: 0
        },
        paper_bgcolor: 'transparent',
        plot_bgcolor: 'transparent',
        shapes,
        layer: 'below'
      };
    },
    getYAxisMeta() {
      const yAxisMeta = {};

      this.data.forEach((datum) => {
        const yAxisMetadata = datum.yAxisMetadata;
        const range = '1';
        const side = 'left';
        const name = yAxisMetadata.name;
        const unit = yAxisMetadata.units;

        yAxisMeta[range] = {
          range,
          side,
          name,
          unit
        };
      });

      return yAxisMeta;
    },
    getXAxisDomain(yAxisMeta) {
      let leftPaddingPerc = 0;
      let rightPaddingPerc = 100;
      let rightSide =
        yAxisMeta && Object.values(yAxisMeta).filter((axisMeta) => axisMeta.side === 'right');
      let leftSide =
        yAxisMeta && Object.values(yAxisMeta).filter((axisMeta) => axisMeta.side === 'left');
      if (yAxisMeta && rightSide.length > 1) {
        rightPaddingPerc = MULTI_AXES_X_PADDING_PERCENT.RIGHT;
      }

      if (yAxisMeta && leftSide.length > 1) {
        leftPaddingPerc = MULTI_AXES_X_PADDING_PERCENT.LEFT;
      }

      return [leftPaddingPerc / 100, rightPaddingPerc / 100];
    },
    getYaxisLayout(yAxisMeta) {
      if (!yAxisMeta) {
        return {};
      }

      const { name, range, side = 'left', unit } = yAxisMeta;
      const title = `${name} ${unit ? '(' + unit + ')' : ''}`;
      const yaxis = {
        automargin: true,
        title
      };

      let yRange = this.yAxisRange;
      if (range === '1') {
        yaxis.range = [yRange.min, yRange.max];

        return yaxis;
      }

      yaxis.range = [yRange.min, yRange.max];
      yaxis.anchor = side.toLowerCase() === 'left' ? 'free' : 'x';
      yaxis.showline = side.toLowerCase() === 'left';
      yaxis.side = side.toLowerCase();
      yaxis.overlaying = 'y';
      yaxis.position = 0.01;

      return yaxis;
    },
    registerListeners() {
      this.unobserveColorChanges = this.openmct.objects.observe(
        this.domainObject,
        'configuration.styles.color',
        this.updateColors
      );
      this.unlistenUnderlay = this.openmct.objects.observe(
        this.domainObject,
        'selectFile',
        this.observeForUnderlayPlotChanges
      );
      this.unlistenUnderlayRanges = this.openmct.objects.observe(
        this.domainObject,
        'configuration.ranges',
        this.updateData
      );
      this.resizeTimer = false;
      if (window.ResizeObserver) {
        this.plotResizeObserver = new ResizeObserver(() => {
          // debounce and trigger window resize so that plotly can resize the plot
          clearTimeout(this.resizeTimer);
          this.resizeTimer = setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
          }, 250);
        });
        this.plotResizeObserver.observe(this.$refs.plotWrapper);
      }
    },
    updateColors() {
      const colors = [];
      const indices = [];
      this.data.forEach((item, index) => {
        const colorExists = this.domainObject.configuration.styles.color;
        indices.push(index);
        if (colorExists) {
          colors.push(this.domainObject.configuration.styles.color);
        } else {
          colors.push(item.marker.color);
        }
      });
      const plotUpdate = {
        'marker.color': colors
      };

      Plotly.restyle(this.$refs.plot, plotUpdate, indices);
    },
    reset() {
      this.isZoomed = false;

      this.updatePlot();
      this.$emit('subscribe');
    },
    updateData() {
      this.updatePlot();
    },
    updateLocalControlPosition() {
      const localControl = this.$refs.localControl;
      localControl.style.display = 'none';

      const plot = this.$refs.plot;
      const bgLayer = this.$el.querySelector('.bglayer');

      const plotBoundingRect = plot.getBoundingClientRect();
      const bgLayerBoundingRect = bgLayer.getBoundingClientRect();

      const top = bgLayerBoundingRect.top - plotBoundingRect.top + 5;
      const left = bgLayerBoundingRect.left - plotBoundingRect.left + 5;

      localControl.style.top = `${top}px`;
      localControl.style.left = `${left}px`;
      localControl.style.display = 'block';
    },
    updatePlot() {
      if (!this.$refs || !this.$refs.plot || this.isZoomed) {
        return;
      }

      Plotly.react(
        this.$refs.plot,
        Array.from(this.data.concat(this.getShapes(this.shapesData))),
        this.getLayout()
      );
    },
    zoom(eventData) {
      const autorange = eventData['xaxis.autorange'];
      const { autosize } = eventData;

      if (autosize || autorange) {
        return;
      }

      this.isZoomed = true;
      this.$emit('unsubscribe');
    },
    getShapes() {
      let markerData = {
        x: [],
        y: []
      };
      const shapes = this.shapesData.map((shapeData, index) => {
        if (
          !shapeData.x ||
          !shapeData.y ||
          !shapeData.x.length ||
          !shapeData.y.length ||
          shapeData.x.length !== shapeData.y.length
        ) {
          return '';
        }

        let text = [];
        shapeData.x.forEach((point) => {
          text.push(`${parseFloat(point).toPrecision(2)}`);
        });

        markerData.x = markerData.x.concat(shapeData.x);
        markerData.y = markerData.y.concat(shapeData.y);

        return {
          x: shapeData.x,
          y: shapeData.y,
          mode: 'text',
          text,
          textfont: {
            family: 'Helvetica Neue, Helvetica, Arial, sans-serif',
            size: '12px',
            color: PATH_COLORS[index]
          },
          opacity: 0.5
        };
      });

      shapes.push({
        x: markerData.x,
        y: markerData.y,
        mode: 'markers',
        marker: {
          size: 6,
          color: MARKER_COLOR
        }
      });

      return shapes;
    }
  }
};
</script>
