<template>
  <q-toolbar
    class="shadow-2 text-accent bg-secondary q-pa-none"
    style="flex-wrap: wrap"
  >
    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/close_icon.png"
      :label="$t('close')"
      @click="closeCurrentWindow"
    />

    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/clean_windows_icon.png"
      :label="$t('clean screen')"
      @click="closeAllWindows"
    />

    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/full_screen_icon.png"
      :label="$t('full screen window')"
      @click="fullscreenWindow"
    />

    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/exit_full_screen_icon.png"
      :label="$t('restore window size')"
      @click="exitFullscreenWindow"
    />

    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/top_window_icon.png"
      :label="$t('win top')"
      @click="topWindow"
    />
    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/lower_window_icon.png"
      :label="$t('win lower')"
      @click="lowerWindow"
    />

    <q-btn
      v-if="$store.state.custom_defines.function_center_control"
      :disable="!$store.state.power_state"
      class="col-auto"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/center_control_icon.png"
      :label="$t('center control')"
      @click="$refs.center_control_dialog.showDialog()"
    />
    <q-btn
      class="col-auto"
      stretch
      stack
      flat
      no-caps
      :disable="power_flag"
      icon="img:pad/toolbar/power_on_icon.png"
      :label="$t('power on')"
      @click="powerOn"
    />
    <q-btn
      class="col-auto"
      stretch
      stack
      flat
      no-caps
      :disable="power_flag"
      icon="img:pad/toolbar/power_off_icon.png"
      :label="$t('power off')"
      @click="powerOff"
    />
    <q-btn
      stretch
      :disable="!$store.state.power_state"
      flat
      stack
      no-caps
      icon="img:pad/toolbar/stop_plan.png"
      :label="$t('stop plan')"
      class="col-auto"
      v-if="plan_running"
      @click="stopPlan"
    />
    <q-btn
      stretch
      :disable="!$store.state.power_state"
      flat
      stack
      no-caps
      icon="img:pad/toolbar/subtitle.png"
      :label="$t('subtitle')"
      class="col-auto"
      @click="$refs.subtitle_dialog.showDialog()"
    />

    <q-btn
      stretch
      :disable="!$store.state.power_state"
      v-if="$store.state.isLedPlayer()"
      flat
      stack
      no-caps
      icon="img:pad/toolbar/edit_window_rect.png"
      :label="$t('toolbar edit window rect')"
      class="col-auto"
      @click="editRect"
    />

    <q-btn
      class="col-auto"
      :disable="!$store.state.power_state"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/other_setting.png"
      :label="$t('other setting')"
    >
      <q-popup-proxy>
        <q-list class="shadow-2 text-primary">
          <q-item
            clickable
            v-close-popup
            @click="$refs.system_setting_dialog.showDialog()"
          >
            <q-item-section avatar>
              <q-icon name="img:pad/toolbar/system_setting.png" />
            </q-item-section>
            <q-item-section>
              {{ $t("system setting") }}
            </q-item-section>
          </q-item>
          <q-item
            clickable
            v-close-popup
            @click="$refs.file_manage_dialog.showDialogAsync()"
          >
            <q-item-section avatar>
              <q-icon name="img:pad/toolbar/file_upload_icon.png" />
            </q-item-section>
            <q-item-section>
              {{ $t("file manage") }}
            </q-item-section>
          </q-item>
          <q-item
            clickable
            v-close-popup
            @click="$refs.background_image_dialog.showDialog()"
          >
            <q-item-section avatar>
              <q-icon name="img:pad/toolbar/wallpaper_icon.png" />
            </q-item-section>
            <q-item-section>
              {{ $t("background image setting") }}
            </q-item-section>
          </q-item>

          <q-item
            clickable
            v-close-popup
            @click="
              $refs.fusion_settings_dialog.showDialog();
              getconfig();
            "
            v-if="$store.state.custom_defines.function_fusion"
          >
            <q-item-section avatar>
              <q-icon style="color: #63bab4;" name="open_with" />
            </q-item-section>
            <q-item-section>
              {{ $t("fusion settings") }}
            </q-item-section>
          </q-item>

          <q-item clickable v-close-popup @click="switchLanguage">
            <q-item-section avatar>
              <q-icon name="img:pad/toolbar/cn_en.png" />
            </q-item-section>
            <q-item-section>
              {{ $t("CN/EN switch") }}
            </q-item-section>
          </q-item>
          <q-item
            v-if="$store.state.advanced_debug"
            clickable
            v-close-popup
            @click="$refs.advanced_debug_dialog.showDialog()"
          >
            <q-item-section avatar>
              <q-icon name="bug_report" color="accent" />
            </q-item-section>
            <q-item-section> AdvancedDebug </q-item-section>
          </q-item>
        </q-list>
      </q-popup-proxy>
    </q-btn>
    <q-space />
    <q-btn
      class="col-1"
      stretch
      stack
      flat
      no-caps
      icon="img:pad/toolbar/logout_icon.png"
      :label="$t('logout')"
      @click="logout"
    />
  </q-toolbar>

  <background-image-dialog ref="background_image_dialog" />
  <file-manage-dialog ref="file_manage_dialog" />
  <center-control-dialog ref="center_control_dialog" />
  <subtitle-dialog ref="subtitle_dialog" />
  <advanced-debug-dialog ref="advanced_debug_dialog" />
  <window-rect-edit-dialog ref="window_rect_edit_dialog" />
  <system-setting-dialog ref="system_setting_dialog" />

  <fusion-settings-dialog ref="fusion_settings_dialog" />

</template>

<script lang="ts">
import { defineComponent, Ref, ref, computed, watch } from "vue";
import { Cookies, SessionStorage, useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useStore } from "src/store";

import FusionSettingsDialog from "src/components/FusionSettingsDialog.vue";

import BackgroundImageDialog from "src/components/BackgroundImageDialog.vue";
import FileManageDialog from "src/components/FileManageDialog.vue";
import SubtitleDialog from "src/components/SubtitleDialog.vue";
import CenterControlDialog from "src/components/CenterControlDialog.vue";
import AdvancedDebugDialog from "src/components/AdvancedDebugDialog.vue";
import WindowRectEditDialog from "src/components/WindowRectEditDialog.vue";
import SystemSettingDialog from "src/components/SystemSettingDialog.vue";

import GlobalData from "src/common/GlobalData";
import { Protocol } from "src/entities/WSProtocol";
import { component } from "v-viewer";
import { EDeviceAttribute } from "src/entities/EDeviceAttribute";

export default defineComponent({
  name: "PadTopToolbarPage",
  components: {
    BackgroundImageDialog,
    FileManageDialog,
    CenterControlDialog,
    SubtitleDialog,
    AdvancedDebugDialog,
    WindowRectEditDialog,
    SystemSettingDialog,
    FusionSettingsDialog
  },
  setup() {
    const $store = useStore();
    const $q = useQuasar();
    const $t = useI18n();
    let set = GlobalData.getInstance().getCurrentClient();
    const window_rect_edit_dialog: Ref<any> = ref(null);

    const plan_running = computed(
      () => $store.state.current_running_plan.trim() != ""
    );

    const power_flag = ref(false);
    watch(
      () => power_flag.value,
      (newV) => {
        if (newV) {
          setTimeout(() => {
            power_flag.value = false;
          }, 1100 * 5);
        }
      }
    );
    const getconfig = () => {
      set?.SetBlendingOption("blending_grids_select_ui", '4')
      set?.SetBlendingOption('blending_grids_select_projector',"0-0");
      set?.SetBlendingOption("blending_grids_select_point", `4:1`)
      set?.SetBlendingOption("blending_grids_show", "1");
      try {
        set?.GetBlendingConfig("").then((res) => {
          let tmp = JSON.parse(res ? res.config : "");
          $store.commit("setEnablefusion", tmp.enable);
          $store.commit("setfusion_configuration", res?.config);
        });
      } catch (error) {}
    };
    return {
      plan_running,
      window_rect_edit_dialog,
      power_flag,
      getconfig,

      toogleFullScreen() {
        if (!$q.fullscreen.isCapable) {
          if ($q.platform.is.ipad) {
            $q.notify({
              type: "warning",
              message:
                $t.t("on the iPad, only Safari supports full screen") + "!",
              position: "top",
              timeout: 1500,
            });
          } else {
            $q.notify({
              type: "warning",
              message:
                $t.t("the current browser does not support full screen") + "!",
              position: "top",
              timeout: 1500,
            });
          }
          return;
        }
        if ($q.fullscreen.isActive) {
          $q.fullscreen.exit();
        } else {
          $q.fullscreen.request().catch((e: any) => {
            console.log(e);
          });
        }
      },
      stopPlan() {
        GlobalData.getInstance().getCurrentClient()?.stopCurrentRunningPlan();
      },
      topWindow() {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == $store.state.selected_window
        );
        if (window) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.focusIn(window.window_id);
        }
      },
      lowerWindow() {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == $store.state.selected_window
        );
        if (window) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.lowerWindow(window.window_id);
        }
      },
      fullscreenWindow() {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == $store.state.selected_window
        );
        if (window) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.windowFullScreen(window.window_id, true);
        }
      },
      exitFullscreenWindow() {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == $store.state.selected_window
        );
        if (window) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.windowFullScreen(window.window_id, false);
        }
      },
      closeCurrentWindow() {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == $store.state.selected_window
        );
        if (window) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.closeWindow(window.window_id);
        }
      },
      closeAllWindows() {
        GlobalData.getInstance().getCurrentClient()?.closeWindow(-1);
      },
      switchLanguage() {
        let language = Cookies.get("language");
        if (!language) {
          language = "zh-CN";
        }

        if (language != "zh-CN" && language != "en-US") {
          language = "zh-CN";
        } else {
          language = language == "zh-CN" ? "en-US" : "zh-CN";
        }
        Cookies.set("language", language, {
          expires: 365,
        });
        window.location.reload();
      },
      logout() {
        const w = window as any;
        if (w.controlLogout && typeof w.controlLogout == "function") {
          w.controlLogout();
        } else {
          Cookies.remove("auto_login");
          SessionStorage.clear();
          try {
            $q.fullscreen.exit();
          } catch {}
          window.location.reload();
        }
      },
      async powerOff() {
        let success = false;
        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.deviceStandByMode();
          if (response) {
            success = response?.success ?? false;
          }
        } catch {}
        if (success) {
          power_flag.value = true;
        }
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("send power off command") +
            (success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      },
      async powerOn() {
        let success = false;
        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.wakeUpDevice();
          if (response) {
            success = response?.success ?? false;
          }
        } catch {}
        if (success) {
          power_flag.value = true;
        }
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("send power on command") +
            (success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      },
      async editRect() {
        if (window_rect_edit_dialog.value) {
          try {
            const window = $store.state.windows.find(
              (element) =>
                element && element.uuid == $store.state.selected_window
            );
            if (window) {
              window_rect_edit_dialog.value.showDialog(window.window_id);
            }
          } catch {}
        }
      },
    };
  },
});
</script>
