<template>
    <!-- 上方的 toolbar -->
    <ToolBar></ToolBar>
    
    <!-- 信标区域 -->
    <Pivot></Pivot>

    <!-- 左上角的 sidebar，用于显示 -->
    <Sidebar></Sidebar>

    <!-- 显示当前信号树形关系 -->
    <!-- 右侧工具合集 -->
    <RightNav></RightNav>
</template>

<script setup>
import { onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';

import { ElLoading } from 'element-plus';

import { emitter, globalLookup, globalSetting, VcdInfo } from '@/hook/global';
import { makeWaveView } from '@/hook/render';
import { getCrossOriginWorkerURL } from '@/hook/network';


import ToolBar from '@/components/toolbar';
import Sidebar from '@/components/sidebar';
import RightNav from '@/components/right-nav.vue';
import Pivot from '@/components/pivot';
import { recoverFromInputFile, recoverSession } from './hook/recover';
import { setDefaultCss } from './hook/css';
import { handleVscodeMessage } from './api/message';

const { t } = useI18n();

// 监听 globalSetting 并录入 localStorage
watch(
    () => globalSetting,
    () => {
        localStorage.setItem('setting', JSON.stringify(globalSetting));
    },
    { deep: true }
);


onMounted(async () => {
    const loading = new ElLoading.service({
        lock: true,
        text: t('loading'),
        background: 'rgba(0, 0, 0, 0.7)'
    });

    // 设置 css 宏
    setDefaultCss();

    // 初始化 localStorage （如果没有的话）
    if (!localStorage.getItem('setting')) {
        localStorage.setItem('setting', JSON.stringify(globalSetting));
    }
    
    // 初始化载入 vcd 文件
    const [arrayBuffer, inputFile, inputViewFile] = await window.readVcdFile();
    
    // 寻找 inputFile 下同名的文件，载入配置中
    await recoverFromInputFile(inputFile, inputViewFile);

    const url = await getCrossOriginWorkerURL(window.workerPath);
    const worker = new Worker(url, {
        name: 'vcd-stream',
        type: 'classic'
    });

    const vcdSourceResponse = await fetch(window.vcdJsPath);
    const vcdSource = await vcdSourceResponse.text();

    const wasmBinaryResponse = await fetch(window.wasmPath);
    const wasmBinary = await wasmBinaryResponse.arrayBuffer();
    
    worker.postMessage({ arrayBuffer, vcdSource, wasmBinary }, [arrayBuffer]);

    worker.addEventListener('message', event => {
        const workerVars = event.data;
        const vcdInfo = workerVars.vcdInfo;
        const signalValues = workerVars.signalValues;

        // console.log(vcdInfo);
        // console.log(signalValues);

        for (const topModule of vcdInfo.wires.body) {
            VcdInfo.topModules.push(topModule);
        }

        globalLookup.status = vcdInfo.status;
        globalLookup.version = vcdInfo.version;
        globalLookup.timescale = vcdInfo.timescale;
        globalLookup.date = vcdInfo.date;
        globalLookup.t0 = vcdInfo.t0 || 0;

        globalLookup.tgcd = workerVars.tgcd;
        globalLookup.time = workerVars.time;        
        globalLookup.maxTime = globalLookup.time * globalLookup.tgcd;
        globalLookup.chango = signalValues;
        makeWaveView();

        // console.log(signalValues['*']);

        // console.log('duration time', globalLookup.time);
        emitter.emit('meta-ready', null);

        // 这一步时，已经加载完成
        // 初始化右侧的模型 treeview 面板
        // 默认第一个模块被选中
        if (VcdInfo.topModules.length > 0) {
            const defaultMod = VcdInfo.topModules[0];
            const wires = defaultMod.body.filter(mod => mod.link);
            emitter.emit('tree-view', wires);
            // 将顶层模块存储进全局对象，以便后续的搜索服务
            for (const mod of VcdInfo.topModules) {
                globalLookup.topModules.push(mod);
            }
        }
        worker.terminate();

        // 根据 recoverConfig 完成现场回复
        recoverSession(VcdInfo.topModules);
        loading.close();
    });
});

// vscode 传递事件
window.addEventListener('message', event => {
    handleVscodeMessage(event);
});

</script>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}


</style>
