<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 { deviceMetricsTimeRange } from '../../config.js';
import { formatUptimeSeconds, getTimeSpans } from '../../utils.js';
import { useStorage } from '@vueuse/core';
const deviceMetricsChartEl = useTemplateRef('device-metrics-chart');

function initChart() {
    // destroy existing chart
    const existingChart = Chart.getChart(deviceMetricsChartEl.value);
    if (existingChart != null) {
        existingChart.destroy();
    }
    // create chart data
    const labels = [];
    const batteryMetrics = [];
    const channelUtilizationMetrics = [];
    const airUtilTxMetrics = [];
    for(const deviceMetric of state.selectedNodeDeviceMetrics) {
        labels.push(moment(deviceMetric.created_at));
        batteryMetrics.push(deviceMetric.battery_level);
        channelUtilizationMetrics.push(deviceMetric.channel_utilization);
        airUtilTxMetrics.push(deviceMetric.air_util_tx);
    }
    // create chart
    new Chart(deviceMetricsChartEl.value, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Battery Level',
                    borderColor: '#3b82f6',
                    backgroundColor: '#3b82f6',
                    pointStyle: false, // no points
                    fill: false,
                    data: batteryMetrics,
                },
                {
                    label: 'Channel Util',
                    borderColor: '#22c55e',
                    backgroundColor: '#22c55e',
                    showLine: false, // no lines between points
                    fill: false,
                    data: channelUtilizationMetrics,
                },
                {
                    label: 'Air Util TX',
                    borderColor: '#f97316',
                    backgroundColor: '#f97316',
                    showLine: false, // no lines between points
                    fill: false,
                    data: airUtilTxMetrics,
                },
            ],
        },
        options: {
            responsive: true,
            borderWidth: 2,
            elements: {
                point: {
                    radius: 2,
                },
            },
            scales: {
                x: {
                    position: 'top',
                    type: 'time',
                    time: {
                        unit: 'day',
                        displayFormats: {
                            day: 'MMM DD', // Jan 01
                        },
                    },
                },
                y: {
                    min: 0,
                    max: 101, // 101 is "Plugged In", need to include for tooltip to work
                    ticks: {
                        callback: (label) => `${label}%`,
                    },
                },
            },
            plugins: {
                legend: {
                    display: false,
                },
                tooltip: {
                    mode: "index",
                    intersect: false,
                    callbacks: {
                        label: (item) => {
                            return `${item.dataset.label}: ${item.formattedValue}%`;
                        },
                    },
                },
            },
        },
    });
}
watch(
  () => state.selectedNodeDeviceMetrics,
  (newValue) => {
    if (newValue !== []) {
        initChart()
    }
  }, {deep: true}
)
onMounted(() => {
    Chart.register(TimeScale, LinearScale, LineController, Tooltip, Legend, PointElement, LineElement)
})
</script>

<template>
    <!-- device metrics -->
    <div>
        <div class="flex bg-gray-200 p-2 font-semibold">
            <div class="my-auto">Device Metrics</div>
            <div class="my-auto ml-auto">
                <select v-model="deviceMetricsTimeRange" 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">

            <!-- device metrics chart -->
            <li>
                <div class="px-4 py-2">
                    <div class="w-full">
                        <canvas id="deviceMetricsChart" style="height:150px;" ref="device-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">Battery Level</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">Channel Utilization</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">Air Util TX</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </li>

            <!-- battery level -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Battery Level</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.battery_level">
                        <span v-if="props.node.battery_level > 100">Plugged In</span>
                        <span v-else>{{ props.node.battery_level }}%</span>
                    </span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- voltage -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Voltage</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.voltage">{{ Number(props.node.voltage).toFixed(2) }}V</span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- channel utilization -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Channel Utilization</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.channel_utilization">{{ Number(props.node.channel_utilization).toFixed(2) }}%</span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- air util tx -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Air Util Tx</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.air_util_tx">{{ Number(props.node.air_util_tx).toFixed(2) }}%</span>
                    <span v-else>???</span>
                </div>
            </li>

            <!-- air util tx -->
            <li class="flex p-3">
                <div class="text-sm font-medium text-gray-900">Uptime</div>
                <div class="ml-auto text-sm text-gray-700">
                    <span v-if="props.node.uptime_seconds">{{ formatUptimeSeconds(props.node.uptime_seconds) }}</span>
                    <span v-else>???</span>
                </div>
            </li>
        </ul>
    </div>
</template>