<script setup lang="ts">
import {useWsStore} from "@/stores/websocket";
import type {IWebsocketService} from "@/composables/websocket/websocketService";
import {getWebsocketService} from "@/composables/websocket/websocketService";
import {onMounted, onUnmounted} from "vue";
import {changeFavicon} from "@/composables/importFavicon";
import {logHelloMessage} from "@/composables/logConsoleMsg";
import NavBar from "@/views/navigation/NavBar.vue";
import type {ControlMsg, ServerMsg} from "@/api";
import {ControlEvent, ControlMsgType} from "@/api";
import {routeCtrlMsg, routeModuleServerMsg} from "@/router/msgRouter";
import {globalNotify} from "@/composables/notification";
import {getTrialDate, isDevMode, isOTAEnabled, isTrialMode} from "@/composables/buildMode";
import {useSystemModule} from "@/composables/useSystemModule";
import {useDataFlowModule} from "@/composables/useDataFlowModule";
import {useUpdateModule} from "@/composables/useUpdateModule";
import {ElMessageBox} from "element-plus";

const wsState = useWsStore();

const onClientCtrl = (msg: ControlMsg) => {
  if (isDevMode()) {
    console.log("App.vue:", msg);
  }
  if (msg.type === ControlMsgType.WS_EVENT) {
    wsState.$patch({state: msg.data as ControlEvent})
    routeCtrlMsg(msg);
    if (msg.data === ControlEvent.CONNECTED) {
      globalNotify("调试器已连接", "success");
    }
  }
};

const onServerMsg = (msg: ServerMsg) => {
  if (isDevMode()) {
    console.log("App.vue:", msg);
  }
  routeModuleServerMsg(msg);
};

let websocketService: IWebsocketService;
onMounted(() => {

  logHelloMessage();
  let host: string;
  if (isDevMode()) {
    host = import.meta.env.VITE_DEVICE_HOST_NAME || "dap.local";
  } else {
    host = window.location.host
  }
  websocketService = getWebsocketService();
  websocketService.init(host, onServerMsg, onClientCtrl);
  websocketService.getSocketStatus();
  changeFavicon();

  useSystemModule();
  useDataFlowModule();

  if (isOTAEnabled()) {
    useUpdateModule();
  }

  if (isTrialMode()) {
    ElMessageBox.alert('感谢您试用串口透传固件，如果觉得好用，可购买标准版支持我，谢谢！', getTrialDate(), {
      confirmButtonText: '好的',
    });
  }
});

onUnmounted(() => {

});
</script>

<template>
  <div class="flex flex-col wt-h-100">
    <header>
      <nav-bar/>
    </header>
    <RouterView/>
  </div>
</template>

<style>
.wt-h-100 {
  height: 100vh;
}
</style>
