import GlobalData from "src/common/GlobalData";
import {
  LocaleMessage,
  DateTimeFormat,
  NumberFormat,
} from "@intlify/core-base";
import { QVueGlobals } from "quasar";
import { Composer, VueMessageType } from "vue-i18n";
import { Store } from "vuex";
import { IWuJieInterface, StateInterface } from "./../store/index";
import EventBus, { EventNamesDefine } from "./EventBus";
import Initializer from "./Initializer";
import ClientConnection from "./ClientConnection";

export class WuJieInitializer {
  public static initialize(
    $wujie: IWuJieInterface,
    $store: Store<StateInterface>,
    $q: QVueGlobals,
    $t: Composer<
      {
        [x: string]: LocaleMessage<VueMessageType>;
      },
      {
        [x: string]: DateTimeFormat;
      },
      {
        [x: string]: NumberFormat;
      },
      string,
      string,
      string
    >
  ) {
    if ($wujie) {
      $wujie.bus.$on("initialize_app", (device_sn: string) => {
        WuJieInitializer.onInitializeApp(device_sn, $wujie, $store, $q, $t);
      });
      setTimeout(() => {
        $wujie.bus.$emit("client_mounted");
      }, 500);
    }
  }

  private static onInitializeApp(
    device_sn: string,
    $wujie: IWuJieInterface,
    $store: Store<StateInterface>,
    $q: QVueGlobals,
    $t: Composer<
      {
        [x: string]: LocaleMessage<VueMessageType>;
      },
      {
        [x: string]: DateTimeFormat;
      },
      {
        [x: string]: NumberFormat;
      },
      string,
      string,
      string
    >
  ) {
    setTimeout(() => {
      const global_data = GlobalData.getInstance();
      const client = global_data.getCurrentClient();
      if (!client) {
        const client_name = "WuJie@" + device_sn;
        console.log(client_name);
        global_data.addClient(client_name, new ClientConnection("", "", ""));
        global_data.setCurrentClientName(client_name);
      }
      if (client) {
        client._is_login = true;
      }
      new Initializer({
        $t,
        $store,
        $q,
      })
        .initialize()
        .then(() => {
          $store.commit("setInitialized");
          if ($wujie) {
            $wujie.bus.$emit("client_initialize_end");
          }
        });
      EventBus.getInstance().emit(EventNamesDefine.WebSocketConnected, this);
    }, 0);
  }
}
