<script lang="ts" setup>
import {useMainLayoutStore} from "~/strores/UseMainLayoutStore";
import {HubConnectionBuilder} from "@microsoft/signalr";
import {FitAddon} from 'xterm-addon-fit'
//导入xtrem
import {Terminal} from "@xterm/xterm";
import "@xterm/xterm/css/xterm.css";
var term: Terminal;
onMounted(()=>{
  term = new Terminal({rows:40,cols:100,smoothScrollDuration:100,scrollback:1000});
  term.open(document.getElementById("terminal") as HTMLElement);
  const fitAddon = new FitAddon();
  term.loadAddon(fitAddon);
  // fitAddon.fit();
  term.focus();
  //绑定输入事件
  term.onData((data) => {
    console.log(data)
    connection.invoke("SendMessage", data)
      .catch(err => {
        console.log("Error while sending message: " + err);
      });
  })
})




const mainLayoutStore = useMainLayoutStore()
const connection = new HubConnectionBuilder()
    .withUrl(`${useRuntimeConfig().public.baseUrl}/TerminalHub`)
    .withAutomaticReconnect()
    .build();
onMounted(async () => {
    connection.on("ReceiveMessage", (message) => {
      term.write(message)
    })
  await connection.start()
      .then(() => {
        console.log("Connection started");
      })
      .catch(err => {
        console.log("Error while starting connection: " + err);
      });
  await connection.invoke("CreateTerminal", mainLayoutStore.SelectServer.id)
        .then(() => {
          console.log("Terminal created")
        })
  setTimeout(()=>{
    connection.invoke("SendMessage","neofetch\n")
  },200)
})
</script>

<template>
  <div class="terminal-box">
    <div id="terminal">
    </div>
  </div>


</template>

<style lang="scss" scoped>
@import "base";

.terminal-box {
  width: 100%;
  padding: $padding;
  background: #000;
  border-radius: $radius*2;
}

#terminal {
  &::-webkit-scrollbar{
    width:0;
  }
}
:deep(.xterm-viewport::-webkit-scrollbar){
  width: 0;
}

</style>