<script setup>
import axios from 'axios';
import moment from 'moment';
import { Chart } from 'chart.js';
import 'chartjs-adapter-moment';
import { onMounted, useTemplateRef, ref, watch } from 'vue';
import { state } from '../store.js';
import { environmentMetricsTimeRange, powerMetricsTimeRange, deviceMetricsTimeRange } from '../config.js';
import DeviceMetricsChart from './NodeInfo/DeviceMetricsChart.vue';
import PowerMetricsChart from './NodeInfo/PowerMetricsChart.vue';
import EnvironmentMetricsChart from './NodeInfo/EnvironmentMetricsChart.vue';
import LoraConfig from './NodeInfo/LoraConfig.vue';
import NodeDetails from './NodeInfo/NodeDetails.vue';
import MqttHistory from './NodeInfo/MqttHistory.vue';
import OtherInfo from './NodeInfo/OtherInfo.vue';
import Share from './NodeInfo/Share.vue';
import Traceroutes from './NodeInfo/Traceroutes.vue';
import Position from './NodeInfo/Position.vue';
import { getNodeColor, getNodeTextColor, copyShareLinkForNode, getTimeSpan, buildPath } from '../utils.js';
const emit = defineEmits(['showPositionHistory']);

function showPositionHistory(id) {
    emit('showPositionHistory', id);
}

function showTraceRoute(traceroute) {
    emit('showTraceRoute', traceroute);
    state.selectedTraceRoute = traceroute;
}

// find node marker by id
function findNodeMarkerById(id) {
    return state.nodeMarkers[id] ?? null;
}

function loadNode(nodeId) {
    loadNodeMqttMetrics(nodeId);
    loadNodeTraceroutes(nodeId);
    loadNodeDeviceMetrics(nodeId);
    loadNodeEnvironmentMetrics(nodeId);
    loadNodePowerMetrics(nodeId);
}

function loadNodeMqttMetrics(nodeId) {
    state.selectedNodeMqttMetrics = [];
    axios.get(buildPath(`/api/v1/nodes/${nodeId}/mqtt-metrics`)).then((response) => {
        state.selectedNodeMqttMetrics = response.data.mqtt_metrics;
    }).catch(() => {
        // do nothing
    });
}

function loadNodeTraceroutes(nodeId) {
    state.selectedNodeTraceroutes = [];
    axios.get(buildPath(`/api/v1/nodes/${nodeId}/traceroutes`), {
        params: {
            count: 5,
        },
    }).then((response) => {
        state.selectedNodeTraceroutes = response.data.traceroutes;
    }).catch(() => {
        // do nothing
    });
}

function loadNodeDeviceMetrics(nodeId) {
    const time = getTimeSpan(deviceMetricsTimeRange.value).amount
    const timeFrom = new Date().getTime() - (time * 1000);
    axios.get(buildPath(`/api/v1/nodes/${nodeId}/device-metrics`), {
        params: {
            time_from: timeFrom,
        },
    }).then((response) => {
        // reverse response, as it's newest to oldest, but we want oldest to newest
        state.selectedNodeDeviceMetrics = response.data.device_metrics.reverse();
    }).catch(() => {
        state.selectedNodeDeviceMetrics = [];
    });
}

function loadNodeEnvironmentMetrics(nodeId) {
    const time = getTimeSpan(environmentMetricsTimeRange.value).amount
    const timeFrom = new Date().getTime() - (time * 1000);
    axios.get(buildPath(`/api/v1/nodes/${nodeId}/environment-metrics`), {
        params: {
            time_from: timeFrom,
        },
    }).then((response) => {
        // reverse response, as it's newest to oldest, but we want oldest to newest
        state.selectedNodeEnvironmentMetrics = response.data.environment_metrics.reverse();
    }).catch(() => {
        state.selectedNodeEnvironmentMetrics = [];
    });
}

function loadNodePowerMetrics(nodeId) {
    const time = getTimeSpan(powerMetricsTimeRange.value).amount
    const timeFrom = new Date().getTime() - (time * 1000);
    axios.get(buildPath(`/api/v1/nodes/${nodeId}/power-metrics`), {
        params: {
            time_from: timeFrom,
        },
    }).then((response) => {
        // reverse response, as it's newest to oldest, but we want oldest to newest
        state.selectedNodePowerMetrics = response.data.power_metrics.reverse();
    }).catch(() => {
        state.selectedNodePowerMetrics = [];
    });
}

watch(
  () => state.selectedNode,
  (newValue) => {
    if (newValue) {
        loadNode(newValue.node_id)
    }
  }, {deep: true}
)

watch(
    () => deviceMetricsTimeRange.value,
    (newValue) => {
        loadNodeDeviceMetrics(state.selectedNode.node_id)
    }
)

watch(
    () => powerMetricsTimeRange.value,
    (newValue) => {
        loadNodePowerMetrics(state.selectedNode.node_id)
    }
)

watch(
    () => environmentMetricsTimeRange.value,
    (newValue) => {
        loadNodeEnvironmentMetrics(state.selectedNode.node_id)
    }
)
</script>
<template>
    <div class="relative z-sidebar" role="dialog" aria-modal="true">

        <!-- overlay -->
        <transition
                enter-active-class="transition-opacity duration-300 ease-linear"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="transition-opacity duration-300 ease-linear"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0">
            <div v-show="state.selectedNode != null" @click="state.selectedNode = null" class="fixed inset-0 bg-gray-900/75"></div>
        </transition>

        <!-- sidebar -->
        <transition
                enter-active-class="transition duration-300 ease-in-out transform"
                enter-from-class="-translate-x-full"
                enter-to-class="translate-x-0"
                leave-active-class="transition duration-300 ease-in-out transform"
                leave-from-class="translate-x-0"
                leave-to-class="-translate-x-full">
            <div v-show="state.selectedNode != null" class="fixed top-0 left-0 bottom-0">
                <div v-if="state.selectedNode != null" class="w-screen h-full max-w-md overflow-hidden">
                    <div class="flex h-full flex-col bg-white shadow-xl">

                        <!-- slideover header -->
                        <div class="p-2 border-b border-gray-200 shadow-sm">
                            <div class="flex">
                                <div class="my-auto mr-2">
                                    <div class="flex rounded-full h-12 w-12 text-white shadow-sm" :style="{backgroundColor: getNodeColor(state.selectedNode.node_id)}" :class="[ `text-[${getNodeTextColor(state.selectedNode.node_id)}]` ]">
                                        <div class="mx-auto my-auto drop-shadow-sm">{{ state.selectedNode.short_name }}</div>
                                    </div>
                                </div>
                                <div class="my-auto mr-auto">
                                    <h2 class="font-bold">Node Info</h2>
                                    <h3 class="text-sm">{{ state.selectedNode.long_name }}</h3>
                                </div>
                                <div class="my-auto ml-2 flex h-7 items-center space-x-2">
                                    <a href="javascript:void(0)" class="rounded-full" @click="copyShareLinkForNode(state.selectedNode.node_id)">
                                        <div class="bg-gray-100 hover:bg-gray-200 p-2 rounded-full">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 256 256" class="size-6">
                                                <path d="M216,112v96a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V112A16,16,0,0,1,56,96H80a8,8,0,0,1,0,16H56v96H200V112H176a8,8,0,0,1,0-16h24A16,16,0,0,1,216,112ZM93.66,69.66,120,43.31V136a8,8,0,0,0,16,0V43.31l26.34,26.35a8,8,0,0,0,11.32-11.32l-40-40a8,8,0,0,0-11.32,0l-40,40A8,8,0,0,0,93.66,69.66Z"></path>
                                            </svg>
                                        </div>
                                    </a>
                                    <a href="javascript:void(0)" class="rounded-full" @click="state.selectedNode = null">
                                        <div class="bg-gray-100 hover:bg-gray-200 p-2 rounded-full">
                                            <svg class="w-6 h-6" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                <path d="M18 6l-12 12"></path>
                                                <path d="M6 6l12 12"></path>
                                            </svg>
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </div>

                        <div class="overflow-y-auto">

                            <!-- no position banner -->
                            <div v-if="findNodeMarkerById(state.selectedNode.node_id) == null" class="flex bg-orange-500 text-white p-2">
                                <div class="my-auto mr-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6">
                                        <path fill-rule="evenodd" d="m11.54 22.351.07.04.028.016a.76.76 0 0 0 .723 0l.028-.015.071-.041a16.975 16.975 0 0 0 1.144-.742 19.58 19.58 0 0 0 2.683-2.282c1.944-1.99 3.963-4.98 3.963-8.827a8.25 8.25 0 0 0-16.5 0c0 3.846 2.02 6.837 3.963 8.827a19.58 19.58 0 0 0 2.682 2.282 16.975 16.975 0 0 0 1.145.742ZM12 13.5a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" clip-rule="evenodd" />
                                    </svg>
                                </div>
                                <div class="my-auto">This node has not reported a position.</div>
                            </div>

                            <div class="flex flex-col my-2">
                                <div class="mx-auto">
                                    <img class="h-48 w-48 rounded object-contain" :src="`/images/devices/${state.selectedNode.hardware_model_name}.png`" alt="" onerror="if(this.src != '/images/no_image.png') this.src = '/images/no_image.png';">
                                </div>
                            </div>

                            <!-- action buttons -->
                            <div class="flex space-x-6 p-2 justify-center">

                                <!-- sent messages -->
                                <a target="_blank" :href="`/api/v1/text-messages/embed?from=${state.selectedNode.node_id}`" class="flex flex-col" title="Messages sent from this Node">
                                    <div class="flex mx-auto mb-1">
                                        <div class="bg-gray-100 hover:bg-gray-200 p-2 rounded-full">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="m15 11.25-3-3m0 0-3 3m3-3v7.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                            </svg>
                                        </div>
                                    </div>
                                    <div class="mx-auto text-sm font-medium text-gray-900">Sent Msgs</div>
                                </a>

                                <!-- received messages -->
                                <a target="_blank" :href="`/api/v1/text-messages/embed?to=${state.selectedNode.node_id}`" class="flex flex-col" title="Messages sent to this Node">
                                    <div class="flex mx-auto mb-1">
                                        <div class="bg-gray-100 hover:bg-gray-200 p-2 rounded-full">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="m9 12.75 3 3m0 0 3-3m-3 3v-7.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                            </svg>
                                        </div>
                                    </div>
                                    <div class="mx-auto text-sm font-medium text-gray-900">Received Msgs</div>
                                </a>

                                <!-- gated messages -->
                                <a target="_blank" :href="`/api/v1/text-messages/embed?gateway_id=${state.selectedNode.node_id}`" class="flex flex-col" title="Messages gated to MQTT by this Node">
                                    <div class="flex mx-auto mb-1">
                                        <div class="bg-gray-100 hover:bg-gray-200 p-2 rounded-full">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418" />
                                            </svg>
                                        </div>
                                    </div>
                                    <div class="mx-auto text-sm font-medium text-gray-900">Gated Msgs</div>
                                </a>

                            </div>

                            <!-- details -->
                            <NodeDetails :node="state.selectedNode"/>
                            <!-- lora config -->
                            <LoraConfig :node="state.selectedNode"/>
                            <!-- position -->
                            <Position @show-position-history="showPositionHistory" :node="state.selectedNode"/>
                            <!-- device metrics -->
                            <DeviceMetricsChart :node="state.selectedNode"/>
                            <!-- environment metrics -->
                            <EnvironmentMetricsChart :node="state.selectedNode"/>
                            <!-- power metrics -->
                            <PowerMetricsChart/>
                            <!-- mqtt -->
                            <MqttHistory />
                            <!-- traceroutes -->
                            <Traceroutes @show-trace-route="showTraceRoute"/>
                            <!-- other -->
                            <OtherInfo :node="state.selectedNode"/>
                            <!-- share -->
                            <Share :node="state.selectedNode"/>

                        </div>

                    </div>
                </div>
            </div>
        </transition>
    </div>
</template>