<script setup lang="ts">
import { useTelemetry } from '@/composables/telemetry';
import {
    computed,
    inject,
    onMounted,
    onUnmounted,
    ref,
    shallowRef,
    type ShallowRef,
    toValue,
    watch,
} from 'vue';
import {
    type TelemetryDataItem,
    WEBSOCKET_SYMBOL,
    type WebsocketHandle,
} from '@/composables/websocket';
import { GRAPH_DATA, type GraphData } from '@/graph/graph';
import { AXIS_DATA, type AxisData } from '@/graph/axis';
import ValueLabel from '@/components/ValueLabel.vue';

const props = defineProps<{
    data: string;
    class?: string;
}>();

const smoothing_distance = 0.15 * 1000;

const text_offset = computed(() => 10);

const { data } = useTelemetry(() => props.data);
const websocket = inject<ShallowRef<WebsocketHandle>>(WEBSOCKET_SYMBOL)!;
const value = websocket.value.listen_to_telemetry(data);

const graph_data = inject<GraphData>(GRAPH_DATA)!;
const axis_data = inject<AxisData>(AXIS_DATA)!;

const min = ref(Infinity);
const max = ref(-Infinity);

const line = ref(Symbol());
const index = computed(() => {
    return graph_data.lines.value.indexOf(line.value);
});
onMounted(() => {
    graph_data.lines.value.push(line.value);
});
onUnmounted(() => {
    graph_data.lines.value = graph_data.lines.value.filter(
        (x) => x != line.value,
    );
});

const memo = shallowRef<TelemetryDataItem[]>([]);
watch([value], ([val]) => {
    const min_x = toValue(graph_data.min_x);
    if (val) {
        const val_t = Date.parse(val.timestamp);
        if (val_t >= min_x) {
            // TODO: Insert this in the right spot in memo
            const new_memo = [val].concat(memo.value);
            const item_val = val.value[data.value!.data_type] as number;
            if (item_val < min.value) {
                min.value = item_val;
            }
            if (item_val > max.value) {
                max.value = item_val;
            }
            memo.value = new_memo;
        }
    }
});
watch([graph_data.min_x, graph_data.max_x], ([min_x, max_x]) => {
    let memo_changed = false;
    const new_memo = ([] as TelemetryDataItem[]).concat(memo.value);
    if (min_x) {
        while (
            new_memo.length > 2 &&
            Date.parse(new_memo[new_memo.length - 2].timestamp) < toValue(min_x)
        ) {
            new_memo.pop();
            memo_changed = true;
        }
    }
    if (max_x) {
        while (
            new_memo.length > 2 &&
            Date.parse(new_memo[1].timestamp) > toValue(max_x)
        ) {
            new_memo.shift();
            memo_changed = true;
        }
    }
    if (memo_changed) {
        let min_val = Infinity;
        let max_val = -Infinity;
        for (const item of new_memo) {
            const item_val = item.value[data.value!.data_type] as number;
            min_val = Math.min(min_val, item_val);
            max_val = Math.max(max_val, item_val);
        }
        memo.value = new_memo;
        max.value = max_val;
        min.value = min_val;
    }
});

watch(
    [min, axis_data.axis_update_watch],
    ([min_val]) => {
        axis_data.min_y_callback(min_val);
    },
    {
        immediate: true,
    },
);

watch(
    [max, axis_data.axis_update_watch],
    ([max_val]) => {
        axis_data.max_y_callback(max_val);
    },
    {
        immediate: true,
    },
);

// This function is somewhat slow
const points = computed(() => {
    let points = '';
    if (memo.value.length == 0 || data.value == null) {
        return '';
    }

    let last_x = graph_data.x_map(toValue(graph_data.max_x));
    let last_t = toValue(graph_data.max_x) + smoothing_distance;

    for (const data_item of memo.value) {
        const t = Date.parse(data_item.timestamp);
        const v = data_item.value[data.value.data_type];
        const x = graph_data.x_map(t);
        const y = axis_data.y_map(v);

        if (last_t - t < smoothing_distance) {
            points += ` ${x},${y}`;
        } else {
            points += ` ${last_x},${y} ${x},${y}`;
        }
        last_x = x;
        last_t = t;
        if (last_x <= 0.0) {
            break;
        }
    }
    return points;
});

const current_value = computed(() => {
    const val = value.value;
    if (val) {
        return val.value[data.value!.data_type] as number;
    }
    return undefined;
});
</script>

<template>
    <g :class="`indexed-color color-${index}`">
        <polyline
            fill="none"
            clip-path="url(#content)"
            :points="points"
        ></polyline>
        <ValueLabel
            v-if="current_value"
            :x="graph_data.x_map(toValue(graph_data.max_x)) + text_offset"
            :y="axis_data.y_map(current_value)"
            :value="current_value"
        >
        </ValueLabel>
    </g>
</template>

<style scoped lang="scss">
@use '@/assets/variables';

polyline {
    stroke-width: 1px;
    stroke: var(--indexed-color);
}
</style>
