<script setup>
const props = defineProps(['node']);
import axios from 'axios';
import moment from 'moment';
import { Chart, TimeScale, LinearScale, LineController, Tooltip, Legend, PointElement, LineElement } from 'chart.js';
import 'chartjs-adapter-moment';
import { onMounted, useTemplateRef, watch } from 'vue';
import { state } from '../../store.js';
import { environmentMetricsTimeRange } from '../../config.js';
import { formatTemperature, getTimeSpans } from '../../utils.js';
const environmentMetricsChartEl = useTemplateRef('environment-metrics-chart');

function initChart() {
    // destroy existing chart
    const existingChart = Chart.getChart(environmentMetricsChartEl.value);
    if (existingChart != null) {
        existingChart.destroy();
    }
    // create chart data
    const labels = [];
    const temperatureMetrics = [];
    const relativeHumidityMetrics = [];
    const barometricPressureMetrics = [];
    for(const deviceMetric of state.selectedNodeEnvironmentMetrics){
        labels.push(moment(deviceMetric.created_at));
        temperatureMetrics.push(deviceMetric.temperature);
        relativeHumidityMetrics.push(deviceMetric.relative_humidity);
        barometricPressureMetrics.push(deviceMetric.barometric_pressure);
    }
    // create chart
    new Chart(environmentMetricsChartEl.value, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Temperature',
                    suffix: 'ºC',
                    borderColor: '#3b82f6',
                    backgroundColor: '#3b82f6',
                    pointStyle: false, // no points
                    fill: false,
                    data: temperatureMetrics,
                    yAxisID: 'y',
                },
                {
                    label: 'Humidity',
                    suffix: '%',
                    borderColor: '#22c55e',
                    backgroundColor: '#22c55e',
                    pointStyle: false, // no points
                    fill: false,
                    data: relativeHumidityMetrics,
                    yAxisID: 'y',
                },
                {
                    label: 'Pressure',
                    suffix: 'hPa',
                    borderColor: '#f97316',
                    backgroundColor: '#f97316',
                    pointStyle: false, // no points
                    fill: false,
                    data: barometricPressureMetrics,
                    yAxisID: 'y1',
                },
            ],
        },
        options: {
            responsive: true,
            borderWidth: 2,
            spanGaps: 1000 * 60 * 60 * 3, // only show lines between metrics with a 3 hour or less gap
            elements: {
                point: {
                    radius: 2,
                },
            },
            scales: {
                x: {
                    position: 'top',
                    type: 'time',
                    time: {
                        unit: 'day',
                        displayFormats: {
                            day: 'MMM DD', // Jan 01
                        },
                    },
                },
                y: {
                    min: -20,
                    max: 100,
                },
                y1: {
                    min: 800,
                    max: 1100,
                    ticks: {
                        stepSize: 10,
                        callback: (label) => `${label} hPa`,
                    },
                    position: 'right',
                    grid: {
                        drawOnChartArea: false, // only want the grid lines for one axis to show up
                    },
                },
            },
            plugins: {
                legend: {
                    display: false,
                },
                tooltip: {
                    mode: "index",
                    intersect: false,
                    callbacks: {
                        label: (item) => {
                            return `${item.dataset.label}: ${item.formattedValue}${item.dataset.suffix}`;
                        },
                    },
                },
            },
        }
    });
}

watch(
  () => state.selectedNodeEnvironmentMetrics,
  (newValue) => {
    if (newValue !== []) {
        initChart()
    }
  }, {deep: true}
)

onMounted(() => {
    Chart.register(TimeScale, LinearScale, LineController, Tooltip, Legend, PointElement, LineElement)
})
</script>

<template>
    <div>
        <div class="flex bg-gray-200 p-2 font-semibold">
            <div class="my-auto">Environment Metrics</div>
            <div class="my-auto ml-auto">
                <select v-model="environmentMetricsTimeRange" class="block w-full rounded-md border-0 py-0.5 pl-2 pr-8 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-blue-500 sm:text-sm sm:leading-6">
                    <option v-for="(range, index) in getTimeSpans()" :value="index">{{ range.name }}</option>
                </select>
            </div>
        </div>
        <ul role="list" class="flex-1 divide-y divide-gray-200">

            <!-- environment metrics chart -->
            <li>
                <div class="px-4 py-2">
                    <div class="w-full">
                        <canvas id="environmentMetricsChart" style="height:150px;" ref="environment-metrics-chart"></canvas>
                        <div class="flex">
                            <div class="mx-auto flex space-x-2">
                                <div class="flex mx-auto">
                                    <div class="my-auto w-2 h-2 bg-blue-500 rounded-full"></div>
                                    <div class="my-auto ml-1 text-sm text-gray-500">Temperature</div>
                                </div>
                                <div class="flex mx-auto">
                                    <div class="my-auto w-2 h-2 bg-green-500 rounded-full"></div>
                                    <div class="my-auto ml-1 text-sm text-gray-500">Humidity</div>
                                </div>
                                <div class="flex mx-auto">
                                    <div class="my-auto w-2 h-2 bg-orange-500 rounded-full"></div>
                                    <div class="my-auto ml-1 text-sm text-gray-500">Pressure</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </li>

            <!-- temperature -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Temperature</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.temperature">{{ formatTemperature(props.node.temperature) }}</span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- relative humidity -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Relative Humidity</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.relative_humidity">{{ Number(props.node.relative_humidity).toFixed(0) }}%</span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- barometric pressure -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Barometric Pressure</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.barometric_pressure">{{ Number(props.node.barometric_pressure).toFixed(1) }}hPa</span>
                    <span v-else>???</span>
                </div>
            </li>
        </ul>
    </div>
</template>