import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import App from "./App.vue";
import router from "./pages/main/router";
import { createPinia } from "pinia";
import { storeToRefs } from "pinia";
import { useServerIpStore } from "./store/ServerIp";
import { useServerPortStore } from "./store/ServerPort";

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);
app.use(ElementPlus);
app.use(router);
app.mount("#app");

const si = useServerIpStore();
const { server_ip } = storeToRefs(si);
const sp = useServerPortStore();
const { server_port } = storeToRefs(sp);

const xhr = new XMLHttpRequest();
xhr.open("GET", window.location.href);
xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      const headers = xhr.getAllResponseHeaders();
      let portRegExp: RegExp = /port:\s*(\d+)/i;
      let ipRegExp: RegExp = /\bip:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/i;
      let portResult: RegExpExecArray | null = portRegExp.exec(headers);
      let ipResult: RegExpExecArray | null = ipRegExp.exec(headers);
      if (portResult) {
        let portValue: string = portResult[1];
        server_port.value = ":" + portValue;
      }
      if (ipResult) {
        let ipValue: string = ipResult[1];
        server_ip.value = ipValue;
      }
      console.log(`当前端口为：${server_port.value}`);
      console.log(`当前ip为：${server_ip.value}`);
    } else {
      console.error("There was a problem with the request.");
    }
  }
};
xhr.send();
