import { reactive, computed } from 'vue';

export const state = reactive({
    // caches
    nodes: [],
    waypoints: [],
    nodeMarkers: {},

    // state
    searchText: '',
    selectedNodeOutlineCircle: null,
    selectedNodeMqttMetrics: [],
    selectedNodeTraceroutes: [],
    selectedNodeDeviceMetrics: [],
    selectedNodePowerMetrics: [],
    selectedNodeEnvironmentMetrics: [],
    selectedNodeToShowNeighbours: null,
    selectedNodeToShowNeighbours: null,
    selectedNodeToShowNeighboursType: null,

    // position history
    selectedNodeToShowPositionHistory: null,
    positionHistoryDateTimeTo: null,
    positionHistoryDateTimeFrom: null,

    // ui
    loading: false,
    settingsVisible: false,
    hardwareStatsVisible: false,
    infoModalVisible: false,
    mobileSearchVisible: false,
    positionHistoryModalExpanded: false,
    announcementVisible: false,
});

export const searchedNodes = computed(() => {
    // search nodes
    const nodes = state.nodes.filter((node) => {
        const matchesId = node.node_id?.toLowerCase()?.includes(state.searchText.toLowerCase());
        const matchesHexId = node.node_id_hex?.toLowerCase()?.includes(state.searchText.toLowerCase());
        const matchesLongName = node.long_name?.toLowerCase()?.includes(state.searchText.toLowerCase());
        const matchesShortName = node.short_name?.toLowerCase()?.includes(state.searchText.toLowerCase());
        return matchesId || matchesHexId || matchesLongName || matchesShortName;
    });

    // order alphabetically by long name
    nodes.sort((nodeA, nodeB) => {
        const nodeALongName = nodeA.long_name || "";
        const nodeBLongName = nodeB.long_name || "";
        return nodeALongName.localeCompare(nodeBLongName);
    });

    // only return the first 500 results to avoid ui lag...
    return nodes.slice(0, 500);
});

export const selectedNodeLatestPowerMetric = computed(() => {
    const [ latestPowerMetric ] = state.selectedNodePowerMetrics.slice(-1);
    return latestPowerMetric;
});