<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (!loading && evt.keyCode == 27) {
          show_dialog = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 35vw">
      <q-form>
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">AdvancedDebug</div>
            <q-space />
            <div>
              <q-btn
                :loading="loading"
                flat
                round
                icon="close"
                color="red"
                v-close-popup
              >
                <q-tooltip>
                  {{ $t("close") }}
                </q-tooltip>
              </q-btn>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section style="max-height: 50vh; width: 35vw" class="scroll">
          <q-list>
            <q-item>
              <q-item-section avatar>{{ $t("function") }}</q-item-section>
              <q-item-section>
                <q-checkbox
                  v-model="function_output_board"
                  :label="$t('output board')"
                  color="cyan"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  v-model="function_center_control"
                  :label="$t('center control')"
                  color="cyan"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
              <q-item-section>
                <q-checkbox
                  v-model="function_mirroring_output"
                  :label="$t('mirroring output')"
                  color="cyan"
                  class="offset-md-1 col"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
              <q-item-section avatar>
                <q-btn
                  @click="setDeviceAttribute"
                  :label="$t('commit')"
                  outline
                  color="primary"
                />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar>
                {{ $t("language") }}
              </q-item-section>
              <q-item-section>
                <div class="row q-gutter-sm">
                  <q-radio
                    color="cyan"
                    :loading="loading"
                    :disable="loading"
                    class="offset-md-1 col"
                    v-model="target_language"
                    val="zh-CN"
                    :label="$t('chinese')"
                  />
                  <q-radio
                    color="cyan"
                    :loading="loading"
                    :disable="loading"
                    class="offset-md-1 col"
                    v-model="target_language"
                    val="en-US"
                    :label="$t('english')"
                  />
                </div>
              </q-item-section>
              <q-item-section avatar>
                <q-btn
                  @click="setSystemLanguage"
                  :label="$t('commit')"
                  outline
                  color="primary"
                />
              </q-item-section>
            </q-item>

            <q-separator class="q-mt-md" />

            <q-item class="q-mt-md">
              <q-item-section>
                <q-btn @click="showDeviceInfo"> {{ $t("device info") }} </q-btn>
              </q-item-section>
            </q-item>

            <q-item class="q-mt-xs">
              <q-item-section>
                <q-btn @click="restartDevice"> {{ $t("restart") }} </q-btn>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            :loading="loading"
            flat
            :label="$t('Cancel')"
            color="primary"
            v-close-popup
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>

<script lang="ts">
import { defineComponent, ref, watch, computed, nextTick } from "vue";
import { useStore } from "src/store";
import { useQuasar, date as $date } from "quasar";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import { Protocol } from "src/entities/WSProtocol";

export default defineComponent({
  name: "ComponentAdvancedDebugDialog",

  setup() {
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();

    let show_dialog = ref(false);
    let loading = ref(false);

    const function_center_control = ref(false);
    const function_output_board = ref(false);
    const function_mirroring_output = ref(false);
    const target_language = ref("zh-CN");

    return {
      show_dialog,
      loading,
      function_center_control,
      function_output_board,
      function_mirroring_output,
      target_language,

      showDialog() {
        show_dialog.value = true;

        setTimeout(async () => {
          try {
            const response = await GlobalData.getInstance()
              .getCurrentClient()
              ?.getDeviceAttribute();
            if (response) {
              nextTick(() => {
                function_center_control.value =
                  (response.attribute &
                    Protocol.EDeviceAttribute.CenterControl) !=
                  0;
                function_output_board.value =
                  (response.attribute &
                    Protocol.EDeviceAttribute.OutputBoard) !=
                  0;
                function_mirroring_output.value =
                  ($store.state.device_attribute &
                    Protocol.EDeviceAttribute.MirroringOutput) !=
                  0;
              });
            }
          } catch {}
        }, 0);
      },
      resetData() {
        loading.value = false;

        function_center_control.value = false;
        function_output_board.value = false;
      },

      restartDevice() {
        GlobalData.getInstance().getCurrentClient()?.restartDevice();
      },
      async showDeviceInfo() {
        const get_time_text = (s: number, show_ss: boolean = true) => {
          console.log(s);
          var time = "";
          var second = s % 60;
          var minute = parseInt((parseInt(s.toString()) / 60).toString()) % 60;
          if (show_ss) {
            time = second + $t.t("SS");
          }
          if (minute >= 1) {
            time = minute + $t.t("MM") + time;
          }
          var hour =
            parseInt((parseInt((s / 60).toString()) / 60).toString()) % 24;
          if (hour >= 1) {
            time = hour + $t.t("HH") + time;
          }
          var day = parseInt(
            (
              parseInt((parseInt((s / 60).toString()) / 60).toString()) / 24
            ).toString()
          );
          if (day >= 1) {
            time = day + $t.t("DD") + time;
          }
          return time;
        };

        let system_run_time = 0;
        let system_idle_time = 0;
        let current_system_time = 0;
        let server_run_time = 0;
        let server_all_run_time = 0;

        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getSystemTimes();
          if (response) {
            system_run_time = response.system_run_time;
            system_idle_time = response.system_idle_time;
            current_system_time = response.current_system_time;
            server_run_time = response.server_run_time;
            server_all_run_time = response.server_all_run_time;
          }
        } catch (e) {
          console.log(e);
        }
        $q.dialog({
          html: true,
          title: "<div class='text-h4'>" + $t.t("device info") + "</div>",
          message: `<div class="text-h6">
          ${$t.t("device resolution")} : ${$store.state.device_screen_width}X${
            $store.state.device_screen_height
          }@${$store.state.device_screen_refresh_rate}<br />
          ${$t.t("system run time")} :  ${get_time_text(system_run_time)} <br />
          ${$t.t("system idle rate")} :  ${(
            (system_idle_time / (system_run_time * 4)) *
            100
          ).toFixed(0)} % <br />
          ${$t.t("server run time")} :  ${get_time_text(server_run_time)} <br />
          ${$t.t("server all run time")} :  ${get_time_text(
            server_all_run_time,
            false
          )} <br />
          ${$t.t("current server system time")} : ${$date.formatDate(
            new Date(current_system_time),
            "YYYY-MM-DD HH:mm:ss"
          )}<br />
          </div>`,
        });
      },
      setDeviceAttribute() {
        let attribute = Protocol.EDeviceAttribute.None;
        if (function_center_control.value) {
          attribute |= Protocol.EDeviceAttribute.CenterControl;
        }
        if (function_output_board.value) {
          attribute |= Protocol.EDeviceAttribute.OutputBoard;
        }
        if (function_mirroring_output.value) {
          attribute |= Protocol.EDeviceAttribute.MirroringOutput;
        }
        GlobalData.getInstance()
          .getCurrentClient()
          ?.setDeviceAttribute(attribute);

        $q.notify({
          color: "positive",
          icon: "done",
          message: $t.t("set device function") + $t.t("success") + "!",
          position: "top",
          timeout: 1500,
        });
      },
      setSystemLanguage() {
        GlobalData.getInstance()
          .getCurrentClient()
          ?.setServerLanguage(target_language.value);
        $q.notify({
          color: "positive",
          icon: "done",
          message: $t.t("set language") + $t.t("success") + "!",
          position: "top",
          timeout: 1500,
        });
      },
    };
  },
});
</script>
