<template>
  <q-dialog persistent v-model="show_dialog" @before-hide="resetData">
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 60vw">
      <q-card-section class="q-ma-none q-pa-sm">
        <div class="row">
          <div class="col-auto text-h6">
            {{ $t("system setting") }}
          </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: 75vh; width: 60vw" class="scroll">
        <q-tabs
          v-model="tab"
          dense
          active-color="primary"
          indicator-color="primary"
          align="justify"
          narrow-indicator
          class="bg-grey-2 text-teal"
        >
          <q-tab
            name="network"
            icon="language"
            :label="$t('network setting')"
            :disable="loading"
          />
          <q-tab
            name="graphics"
            icon="picture_in_picture_alt"
            :label="$t('graphics setting')"
            :disable="loading"
          />
          <q-tab
            name="other"
            icon="build"
            :label="$t('other setting')"
            :disable="loading"
          />
          <q-tab
            name="output_board"
            icon="save"
            :label="$t('output board setting')"
            :disable="loading"
          />
        </q-tabs>
        <q-separator />
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="network" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="network_form" @submit="applyNetwork">
                  <q-list>
                    <q-item>
                      <q-item-section avatar class="width_5_1">{{
                        $t("auto ip") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="auto_ip"
                          :options="[$t('enable'), $t('disable')]"
                          :loading="loading"
                          :disable="loading"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item v-if="auto_ip != $t('enable')">
                      <q-item-section avatar class="width_5_1">{{
                        $t("ip address") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="ip_address"
                          :loading="loading"
                          :disable="loading"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item v-if="auto_ip != $t('enable')">
                      <q-item-section avatar class="width_5_1">{{
                        $t("gateway") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="loading"
                          v-model="gateway"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item v-if="auto_ip != $t('enable')">
                      <q-item-section avatar class="width_5_1">{{
                        $t("netmask") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          :loading="loading"
                          :disable="loading"
                          v-model="netmask"
                          maxlength="15"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isIpAddress(val) ||
                              $t('Please input vaild ip address'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_1">{{
                        $t("mac address") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="mac_address"
                          :loading="loading"
                          :disable="loading"
                          maxlength="17"
                          :rules="[
                            (val) =>
                              (val && val.length > 0) ||
                              $t('Please type something'),
                            (val) =>
                              isMacAddress(val) ||
                              $t('Please input vaild mac address') +
                                '  (XX:XX:XX:XX:XX:XX)',
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="graphics" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-form ref="graphics_form" @submit="applyGraphics">
                  <q-list>
                    <q-item>
                      <q-item-section avatar class="width_5_2">{{
                        $t("brightness") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="brightness"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2">{{
                        $t("contrast") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="contrast"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2">{{
                        $t("hue") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-input
                          v-model="hue"
                          :loading="loading"
                          :disable="loading"
                          type="number"
                          :rules="[
                            (val) =>
                              (val != null &&
                                val != undefined &&
                                val.toString().length > 0) ||
                              $t('Please type something'),
                          ]"
                          lazy-rules
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2_2">{{
                        $t("device resolution") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="device_resolution"
                          :loading="loading"
                          :disable="loading"
                          :options="device_resolution_options"
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2_2">{{
                        $t("device rotate") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="device_rotate"
                          :loading="loading"
                          :disable="loading"
                          :options="device_rotate_options"
                          emit-value
                          map-options
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section avatar class="width_5_2_2">{{
                        $t("output board resolution") + ":"
                      }}</q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="output_board_resolution"
                          :loading="loading"
                          :disable="loading"
                          :options="output_board_resolution_options"
                        />
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-form>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="other" class="_panel">
            <q-card class="fit">
              <q-scroll-area style="height: 55vh">
                <q-card-section>
                  <q-form ref="other_form" @submit="applyOther">
                    <q-list>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("output audio card") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_audio_card"
                            :loading="loading"
                            :disable="loading"
                            :options="output_audio_card_options"
                            emit-value
                            map-options
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="false">
                        <q-item-section avatar class="width_5_3">{{
                          $t("muted") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="system_muted"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="false && system_muted == $t('off')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("volume") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="system_volume"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("use ntp") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="use_ntp"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('enable'), $t('disable')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('enable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("ntp server") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="ntp_server"
                            :loading="loading"
                            :disable="loading"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('enable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("ntp sync delay(S)") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="ntp_sync_delay"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item v-if="use_ntp == $t('disable')">
                        <q-item-section avatar class="width_5_3">{{
                          $t("current datetime") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="current_date"
                            :loading="loading"
                            :disable="loading"
                            type="date"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="current_time"
                            :loading="loading"
                            :disable="loading"
                            type="time"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_3">{{
                          $t("time zone") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="time_zone"
                            :loading="loading"
                            :disable="loading"
                            :options="time_zone_options"
                          />
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-form>
                </q-card-section>
              </q-scroll-area>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="output_board" class="_panel">
            <q-card class="fit">
              <q-card-section>
                <q-scroll-area style="height: 55vh">
                  <q-form ref="output_board_form" @submit="applyOutputBoard">
                    <q-list>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("wall row") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_wall_row"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("wall col") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_wall_col"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("splicing") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_splicing"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("vertical blanking") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_vertical_blanking"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("horizon blanking") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_horizon_blanking"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("rotate") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_rotate"
                            :loading="loading"
                            :disable="loading"
                            :options="output_board_rotate_options"
                            emit-value
                            map-options
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("volume") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="output_board_volume"
                            :loading="loading"
                            :disable="loading"
                            type="number"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                            ]"
                            lazy-rules
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="width_5_4">{{
                          $t("mute") + ":"
                        }}</q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="output_board_mute"
                            :loading="loading"
                            :disable="loading"
                            :options="[$t('on'), $t('off')]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section>
                          <q-btn
                            class="q-mx-xl"
                            :label="$t('restore output board')"
                            @click="restoreOutputBoard"
                          ></q-btn>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-form>
                </q-scroll-area>
              </q-card-section>
            </q-card>
          </q-tab-panel>
        </q-tab-panels>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          :loading="loading"
          flat
          :label="$t('revert and exit')"
          color="primary"
          v-close-popup
        />
        <q-btn
          :loading="loading"
          flat
          :label="$t('revert')"
          color="primary"
          @click="refresh_all"
        />
        <q-btn
          :loading="loading"
          flat
          :label="$t('apply')"
          color="primary"
          @click="apply"
        />
        <q-btn
          v-if="false"
          :loading="loading"
          flat
          :label="$t('apply and exit')"
          color="primary"
          @click="applyAndExit"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.width_5_1 {
  width: 20%;
}

.width_5_2 {
  width: 10%;
}

.width_5_2_2 {
  width: 18%;
}

.width_5_3 {
  width: 20%;
}

.width_5_4 {
  width: 20%;
}

._panel {
  padding: 3px;
  height: 60vh;
}
</style>

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

const _time_zones = [
  "UTC-12(Central Pacific)",
  "UTC-11(Central Pacific)",
  "UTC-10(Honolulu of USA)",
  "UTC-9(Alaska of USA)",
  "UTC-8(California of USA)",
  "UTC-7(Phoenix of USA, Arizona of USA)",
  "UTC-6(Chicago of USA, Mexico)",
  "UTC-5(New York of USA)",
  "UTC-4(Republic of Chile)",
  "UTC-3(Brazil, Argentina)",
  "UTC-2(Mid Atlantic)",
  "UTC-1(West African continent)",
  "UTC(England, Portugal)",
  "UTC+1(Spain, France, Germany, ...)",
  "UTC+2(Turkey, South Africa, Rome, Egypt, ...)",
  "UTC+3(Moscow of Russia, Iran)",
  "UTC+4(The united Arab emirates)",
  "UTC+5(Pakistan, India)",
  "UTC+6(Bangladesh, Myanmar, Xinjiang Autonomous Region of China)",
  "UTC+7(Thailand, Malaysia, Singapore)",
  "UTC+8(Beijing of China, Philippines)",
  "UTC+9(Japan)",
  "UTC+10(Vladivostok of Russia, Guam, Australia)",
  "UTC+11(Solomon Islands)",
  "UTC+12(New Zealand)",
];

export default defineComponent({
  name: "SystemSettingDialog",

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

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

    let tab = ref("network");

    let auto_ip = ref($t.t("enable"));
    let ip_address = ref("127.0.0.1");
    let gateway = ref("127.0.0.1");
    let netmask = ref("127.0.0.1");
    let mac_address = ref("11:22:33:44:55:66");

    let brightness = ref(0);
    let contrast = ref(0);
    let hue = ref(0);

    let old_resolution: string = "";
    let old_rotate: number = 0;
    let device_resolution = ref("");
    let device_resolution_options = ref(["11", "22", "33"]);
    let device_rotate = ref(0);
    let device_rotate_options = ref([
      {
        label: "0°",
        value: 0,
      },
      {
        label: "90°",
        value: 1,
      },
      {
        label: "180°",
        value: 2,
      },
      {
        label: "270°",
        value: 3,
      },
      {
        label: $t.t("horizontal flipped"),
        value: 4,
      },
      {
        label: $t.t("horizontal flipped") + "90°",
        value: 5,
      },
      {
        label: $t.t("horizontal flipped") + "180°",
        value: 6,
      },
      {
        label: $t.t("horizontal flipped") + "270°",
        value: 7,
      },
    ]);
    let output_board_resolution = ref("");
    let output_board_resolution_options = ref(["1", "2", "3"]);

    let system_muted = ref($t.t("off"));
    let system_volume = ref(100);
    let output_audio_card_options = ref([
      { label: "3.5mm", value: "3.5mm" },
      { label: "HDMI1", value: "HDMI1" },
    ]);
    let old_output_audio_card = "";
    let output_audio_card = ref(output_audio_card_options.value[0].value);
    let use_ntp = ref($t.t("enable"));
    let ntp_server = ref("");
    let ntp_sync_delay = ref(180);
    let current_date = ref("");
    let current_time = ref("");
    let time_zone = ref("");
    let time_zone_options: Ref<string[]> = ref([]);
    for (const item of _time_zones) {
      time_zone_options.value.push($t.t(item));
    }

    let network_form: Ref<any> = ref(null);
    let other_form: Ref<any> = ref(null);
    let graphics_form: Ref<any> = ref(null);
    let output_board_form: Ref<any> = ref(null);

    let output_board_wall_row = ref(2);
    let output_board_wall_col = ref(2);
    let output_board_splicing = ref($t.t("on"));
    let output_board_vertical_blanking = ref(0);
    let output_board_horizon_blanking = ref(0);
    let output_board_rotate = ref(0);
    const output_board_rotate_options = ref([
      { label: "0°", value: 0 },
      { label: "180°", value: 1 },
    ]);
    let output_board_volume = ref(100);
    let output_board_mute = ref($t.t("on"));

    const refresh_network = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        auto_ip.value =
          config.auto_ip_address != "0" ? $t.t("enable") : $t.t("disable");
        gateway.value = config.gateway;
        netmask.value = config.subnet_mask;
        mac_address.value = config.mac_address;
        ip_address.value = $store.state.device_ip_address;
      }
    };

    const refresh_graphics = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        setTimeout(async () => {
          const support_resolutions = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getSupportResolutions();
          if (support_resolutions) {
            output_board_resolution_options.value = [];
            for (const item of Object.keys(
              support_resolutions.output_board_support_resolutions
            ).sort()) {
              output_board_resolution_options.value.push(
                (support_resolutions.output_board_support_resolutions as any)[
                  item
                ]
              );
            }
            device_resolution_options.value = [];
            for (const item of Object.keys(
              support_resolutions.device_support_resolutions
            )) {
              device_resolution_options.value.push(item);
            }

            {
              const val = output_board_resolution_options.value.find(
                (element) =>
                  element &&
                  element == support_resolutions.current_output_board_resolution
              );
              output_board_resolution.value =
                val ?? output_board_resolution_options.value[0];
            }

            {
              const val = device_resolution_options.value.find(
                (element) =>
                  element &&
                  element == support_resolutions.current_device_resolution
              );
              device_resolution.value =
                val ?? device_resolution_options.value[0];
              old_resolution = device_resolution.value;
            }
          }
        }, 1);

        brightness.value = parseInt(config.graphics_brightness.toString());
        contrast.value = parseInt(config.graphics_contrast.toString());
        hue.value = parseInt(config.graphics_hue.toString());

        device_rotate.value = parseInt(config.device_rotate.toString());
        old_rotate = device_rotate.value;
      }
    };

    const refresh_other = () => {
      const config = GlobalData.getInstance()?.applicationConfig;
      if (config) {
        output_audio_card.value = config.output_audio_card;
        old_output_audio_card = output_audio_card.value;
        let muted = parseInt(config.system_muted.toString());
        if (isNaN(muted)) {
          muted = 0;
        }
        system_muted.value = muted ? $t.t("on") : $t.t("off");
        system_volume.value = config.system_volume;

        use_ntp.value =
          config.use_ntp != "0" ? $t.t("enable") : $t.t("disable");
        ntp_server.value = config.ntp_server;
        ntp_sync_delay.value = parseInt(config.ntp_sync_delay);
        if (isNaN(ntp_sync_delay.value)) {
          ntp_sync_delay.value = 180;
        }
        try {
          time_zone.value = time_zone_options.value[config.time_zone];
        } catch (e) {
          time_zone.value = time_zone_options.value[0];
        }

        const timeStamp = Date.now();
        current_date.value = date.formatDate(timeStamp, "YYYY-MM-DD");
        current_time.value = date.formatDate(timeStamp, "HH:mm:ss");
      }
    };

    const refresh_output_board = async () => {
      const settings = await GlobalData.getInstance()
        .getCurrentClient()
        ?.getOutputBoardSetting();
      if (settings) {
        output_board_wall_row.value = settings.wall_row;
        output_board_wall_col.value = settings.wall_col;
        output_board_splicing.value = settings.splicing
          ? $t.t("on")
          : $t.t("off");
        output_board_vertical_blanking.value = settings.vertical_blanking;
        output_board_horizon_blanking.value = settings.horizon_blanking;
        output_board_rotate.value = settings.rotate;
        output_board_volume.value = settings.volume;
        output_board_mute.value = settings.mute ? $t.t("on") : $t.t("off");
      }
    };

    const refresh_all = () => {
      refresh_network();
      refresh_graphics();
      refresh_other();
      refresh_output_board();
    };

    const wait_for = async (delay_ms: number) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(null);
        }, delay_ms);
      });
    };

    const applyNetwork = async () => {
      loading.value = true;
      const request = new Protocol.SetSystemNetworkRequestEntity();
      request.auto_ip = auto_ip.value == $t.t("enable");
      request.ip_address = ip_address.value;
      request.gtateway = gateway.value;
      request.net_mask = netmask.value;
      request.mac_address = mac_address.value;

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setSystemNetwork(request);
        setTimeout(() => {
          if (request.ip_address != $store.state.device_ip_address) {
            setTimeout(() => {
              SessionStorage.clear();
              if (
                window.location.hostname.toLowerCase() == "192.168.1.1" ||
                window.location.hostname.toLowerCase() == "localhost"
              ) {
                window.location.reload();
              } else {
                window.location.hostname = request.ip_address;
              }
            }, 2500);
          }
        }, 1000 * 10);
        success = true;
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set system network") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const applyGraphics = async () => {
      loading.value = true;
      const request = new Protocol.SetSystemGraphicsRequestEntity();
      request.brightness = parseInt(brightness.value.toString());
      request.contrast = parseInt(contrast.value.toString());
      request.hue = parseInt(hue.value.toString());
      request.output_board_resolution = output_board_resolution.value;
      request.device_resolution = device_resolution.value;
      request.rotate = parseInt(device_rotate.value.toString());

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setSystemGraphics(request);
        await wait_for(1000 * 3);
        success = true;
        if (
          old_resolution != device_resolution.value ||
          old_rotate != device_rotate.value
        ) {
          try {
            $q.dialog({
              title: "Confirm",
              message:
                $t.t(
                  "major graphics parameters have been changed and need to be restarted to take effect. Restart the system"
                ) + "?",
              cancel: true,
              persistent: true,
            }).onOk(async () => {
              await GlobalData.getInstance()
                .getCurrentClient()
                ?.restartDevice(1000 * 3);
              $q.notify({
                color: "positive",
                icon: "done",
                message:
                  $t.t("restart command send") +
                  $t.t("success") +
                  "!" +
                  $t.t("the system will reboot after the setup is complete") +
                  "!",
                position: "top",
                timeout: 2500,
              });
            });
          } catch {}
        }
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set system graphics") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      old_resolution = device_resolution.value;
      old_rotate = device_rotate.value;
      loading.value = false;
    };

    const applyOther = async () => {
      loading.value = true;

      const request = new Protocol.SetSystemOtherRequestEntity();

      request.system_volume = parseInt(system_volume.value.toString());
      request.system_muted = system_muted.value == $t.t("on");
      request.output_audio_card = output_audio_card.value;
      request.use_ntp = use_ntp.value == $t.t("enable");
      request.ntp_sync_delay = parseInt(ntp_sync_delay.value.toString());
      request.ntp_server = ntp_server.value;
      request.time_zone = time_zone_options.value.findIndex(
        (element) => element && element == time_zone.value
      );
      if (request.time_zone < 0) {
        request.time_zone =
          GlobalData.getInstance().applicationConfig?.time_zone ?? 21;
      }
      request.datetime = current_date.value + " " + current_time.value;

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setSystemOther(request);
        success = true;
        if (old_output_audio_card != request.output_audio_card) {
          try {
            $q.dialog({
              title: "Confirm",
              message:
                $t.t(
                  "the sound card takes effect only after it is restarted. Restart the system"
                ) + "?",
              cancel: true,
              persistent: true,
            }).onOk(async () => {
              await GlobalData.getInstance()
                .getCurrentClient()
                ?.restartDevice(1000 * 3);
              $q.notify({
                color: "positive",
                icon: "done",
                message:
                  $t.t("restart command send") +
                  $t.t("success") +
                  "!" +
                  $t.t("the system will reboot after the setup is complete") +
                  "!",
                position: "top",
                timeout: 2500,
              });
            });
          } catch {}
        }
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set system other") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      old_output_audio_card = request.output_audio_card;
      loading.value = false;
    };

    const applyOutputBoard = async () => {
      loading.value = true;
      const request = new Protocol.SetOutputBoardSettingRequestEntity();
      request.wall_col = parseInt(output_board_wall_col.value.toString());
      request.wall_row = parseInt(output_board_wall_row.value.toString());
      request.splicing = output_board_splicing.value == $t.t("on");
      request.vertical_blanking = parseInt(
        output_board_vertical_blanking.value.toString()
      );
      request.horizon_blanking = parseInt(
        output_board_horizon_blanking.value.toString()
      );
      request.rotate = parseInt(output_board_rotate.value.toString());
      request.volume = parseInt(output_board_volume.value.toString());
      request.mute = output_board_mute.value == $t.t("on");

      let success = false;
      try {
        await GlobalData.getInstance()
          .getCurrentClient()
          ?.setOutputBoardSetting(request);
        success = true;
      } catch {}
      $q.notify({
        color: success ? "positive" : "negative",
        icon: success ? "done" : "warning",
        message:
          $t.t("set output board") +
          (success ? $t.t("success") : $t.t("fail")) +
          "!",
        position: "top",
        timeout: 2500,
      });
      loading.value = false;
    };

    const apply = () => {
      switch (tab.value) {
        case "network":
          network_form.value.submit();
          break;
        case "graphics":
          graphics_form.value.submit();
          break;
        case "other":
          other_form.value.submit();

          break;
        case "output_board":
          output_board_form.value.submit();
          break;
      }
    };
    const restoreOutputBoard = () => {
      GlobalData.getInstance().getCurrentClient()?.restoreOutputBoard();
    };

    return {
      show_dialog,
      loading,
      tab,
      auto_ip,
      ip_address,
      gateway,
      netmask,
      mac_address,
      brightness,
      contrast,
      hue,
      device_rotate,
      device_rotate_options,
      device_resolution,
      device_resolution_options,
      output_board_resolution,
      output_board_resolution_options,
      output_audio_card,
      output_audio_card_options,
      system_muted,
      system_volume,
      use_ntp,
      ntp_server,
      ntp_sync_delay,
      current_date,
      current_time,
      time_zone,
      time_zone_options,
      output_board_mute,
      output_board_volume,
      output_board_rotate_options,
      output_board_rotate,
      output_board_horizon_blanking,
      output_board_vertical_blanking,
      output_board_splicing,
      output_board_wall_col,
      output_board_wall_row,
      network_form,
      other_form,
      graphics_form,
      output_board_form,
      refresh_all,
      apply,
      restoreOutputBoard,
      applyNetwork,
      applyGraphics,
      applyOther,
      applyOutputBoard,
      loga(a: any) {
        console.log(a);
      },
      showDialog() {
        show_dialog.value = true;

        refresh_all();
      },
      resetData() {
        loading.value = false;
        tab.value = "network";
      },
      async applyAndExit() {
        await apply();
        show_dialog.value = false;
      },
      isIpAddress(str: string) {
        return (
          str == "localhost" ||
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(
            str
          )
        );
      },
      isMacAddress(str: string) {
        return /([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}/.test(str);
      },
    };
  },
});
</script>
