<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: 40vw">
      <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"
                :disable="loading"
                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: 60vh; width: 40vw" class="scroll">
          <q-list>
            <q-item>
              <q-item-section avatar>{{ $t("product") }}</q-item-section>
              <q-item-section>
                <q-radio
                  v-model="selected_product"
                  val=""
                  :label="$t('normal')"
                  color="cyan"
                  class="offset-md-1 col"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
              <q-item-section>
                <q-radio
                  v-model="selected_product"
                  val="magic_wall"
                  :label="$t('magic wall')"
                  color="cyan"
                  class="offset-md-1 col"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
              <q-item-section>
                <q-radio
                  v-model="selected_product"
                  val="fusion"
                  :label="$t('fusion')"
                  color="cyan"
                  class="offset-md-1 col"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
            </q-item>
            <q-item v-if="selected_product == 'fusion'">
              <q-item-section avatar>{{ $t("fusion") }}</q-item-section>
              <q-item-section>
                <div class="row" v-for="(row, row_index) in 3" :key="row">
                  <q-radio
                    v-for="(item, item_index) in 3"
                    :key="row_index * 3 + item"
                    v-model="function_fusion_count"
                    :val="row_index * 3 + item"
                    :label="
                      (row_index * 3 + item).toString() +
                      $t(' ') +
                      $t('fusion out')
                    "
                    color="cyan"
                    class="col"
                    :class="item_index ? 'offset-md-1 ' : ''"
                    :loading="loading"
                    :disable="loading"
                  />
                </div>
              </q-item-section>
            </q-item>
            <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>
            <q-item>
              <q-item-section avatar></q-item-section>
              <q-item-section>
                <q-checkbox
                  v-model="function_custom_ISV"
                  :label="$t('Custom ISV')"
                  color="cyan"
                  class="col"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section> </q-item-section>
              <q-item-section>
                <q-btn
                  @click="setDeviceAttributeAndProduct"
                  :label="$t('commit')"
                  no-caps
                  outline
                  class="q-px-lg"
                  color="primary"
                />
              </q-item-section>
              <q-item-section> </q-item-section>
            </q-item>
            <q-separator />
            <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')"
                  no-caps
                  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 no-caps @click="showDeviceInfo">
                  {{ $t("device info") }}
                </q-btn>
              </q-item-section>
            </q-item>

            <q-item class="q-mt-xs">
              <q-item-section>
                <q-btn no-caps @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')"
            no-caps
            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 {
  EDeviceAttribute,
  EDeviceAttributeHelper,
} from "src/entities/EDeviceAttribute";

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_custom_ISV = ref($store.state.custom_defines.is_custom_isv);
    const function_center_control = ref(
      $store.state.custom_defines.function_center_control
    );
    const function_output_board = ref(
      $store.state.custom_defines.function_output_board
    );
    const function_mirroring_output = ref(
      $store.state.custom_defines.function_mirroring_output
    );
    const function_magic_wall = ref(
      $store.state.custom_defines.function_magic_wall
    );
    const function_fusion = ref($store.state.custom_defines.function_fusion);
    const function_fusion_count = ref(0);
    const target_language = ref("zh-CN");
    const selected_product = ref("");

    watch(
      () => selected_product.value,
      (newValue) => {
        function_fusion.value = newValue == "fusion";
        function_magic_wall.value = newValue == "magic_wall";
      }
    );

    const getFinalAttribute = () => {
      let attribute = EDeviceAttribute.None;
      if (function_center_control.value) {
        attribute |= EDeviceAttribute.CenterControl;
      }
      if (function_output_board.value) {
        attribute |= EDeviceAttribute.OutputBoard;
      }
      if (function_mirroring_output.value) {
        attribute |= EDeviceAttribute.MirroringOutput;
      }

      if (function_custom_ISV.value) {
        attribute |= EDeviceAttribute.CustomISV;
      }
      if (function_magic_wall.value) {
        attribute |= EDeviceAttribute.ProductMagicWall;
      }
      if (function_fusion.value) {
        attribute |= EDeviceAttributeHelper.getProdictFusionAttributeByIndex(
          function_fusion_count.value
        );
      }
      return attribute;
    };

    return {
      show_dialog,
      loading,
      function_center_control,
      function_output_board,
      function_custom_ISV,
      function_magic_wall,
      function_fusion,
      function_fusion_count,
      function_mirroring_output,
      target_language,
      selected_product,

      showDialog() {
        show_dialog.value = true;

        function_custom_ISV.value = $store.state.custom_defines.is_custom_isv;
        function_center_control.value =
          $store.state.custom_defines.function_center_control;
        function_output_board.value =
          $store.state.custom_defines.function_output_board;
        function_mirroring_output.value =
          $store.state.custom_defines.function_mirroring_output;
        function_magic_wall.value =
          $store.state.custom_defines.function_magic_wall;
        function_fusion.value = $store.state.custom_defines.function_fusion;
        function_fusion_count.value =
          EDeviceAttributeHelper.getProductFusionOutputCountDefault(
            $store.state.device_attribute,
            1
          );

        if (function_magic_wall.value) {
          selected_product.value = "magic_wall";
        } else if (function_fusion.value) {
          selected_product.value = "fusion";
        }
      },
      resetData() {
        loading.value = false;

        function_center_control.value = false;
        function_output_board.value = false;
        function_mirroring_output.value = false;
        function_custom_ISV.value = false;
        function_magic_wall.value = false;
        function_fusion.value = false;
        selected_product.value = "";
      },

      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>`,
        });
      },
      setDeviceAttributeAndProduct() {
        let attribute = getFinalAttribute();
        GlobalData.getInstance()
          .getCurrentClient()
          ?.setDeviceAttribute(attribute);

        $q.notify({
          color: "positive",
          icon: "done",
          message: $t.t("set device function") + $t.t("success") + "!",
          position: "top",
          timeout: 1500,
        });
      },
      setDeviceAttribute() {
        let attribute = getFinalAttribute();

        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,
        });
      },
      changeMagic() {
        if (function_magic_wall.value) {
          function_fusion.value = false;
        }
      },
      changeFusion() {
        if (function_fusion.value) {
          function_magic_wall.value = false;
        }
      },
    };
  },
});
</script>