<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 @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ upgrade_type }}{{ $t("upgrade") }}
            </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>
                <q-select
                  :label="$t('upgrade type')"
                  :hint="$t('please input') + $t('upgrade type') + ':'"
                  :options="select_options"
                  v-model="upgrade_type"
                  @update:model-value="file_count = 0"
                >
                </q-select>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-uploader
                  v-show="upgrade_type == $t('software')"
                  class="full-width"
                  ref="uploader_software"
                  :url="upload_url_software"
                  method="post"
                  :headers="generatorFileUploadHeaders"
                  :label="$t('select software upgrade file') + ':'"
                  accept=".zip"
                  :hide-upload-btn="true"
                  @uploaded="onUploaded"
                  @failed="onFailed"
                  @added="(files) => files && (file_count += files.length)"
                  @removed="(files) => files && (file_count -= files.length)"
                />
                <q-uploader
                  v-show="upgrade_type == $t('rootfs')"
                  class="full-width"
                  ref="uploader_rootfs"
                  :url="upload_url_rootfs"
                  method="post"
                  :headers="generatorFileUploadHeaders"
                  :label="$t('select rootfs upgrade file') + ':'"
                  accept=".img"
                  :hide-upload-btn="true"
                  @uploaded="onUploaded"
                  @failed="onFailed"
                  @added="(files) => files && (file_count += files.length)"
                  @removed="(files) => files && (file_count -= files.length)"
                />
              </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-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            :loading="loading"
            no-caps
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>

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

export default defineComponent({
  name: "ComponentUpgradeDialog",

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

    let show_dialog = ref(false);
    let uploader_software: any = ref(null);
    let uploader_rootfs: any = ref(null);
    let loading = ref(false);
    let upload_url_software = ref("");
    let upload_url_rootfs = ref("");
    let file_count = ref(0);

    let select_options = [$t.t("software"), $t.t("rootfs")];
    let upgrade_type = ref($t.t("software"));

    return {
      show_dialog,
      loading,
      upload_url_software,
      upload_url_rootfs,
      uploader_software,
      uploader_rootfs,
      file_count,
      upgrade_type,
      select_options,
      generatorFileUploadHeaders(files: File[]) {
        if (files.length > 0) {
          return [
            {
              name: HttpProtocol.kHeaderXProductName,
              value: HttpProtocol.kHeaderDefaultValueXProductName,
            },
            {
              name: HttpProtocol.kHeaderXFileLength,
              value: files[0].size,
            },
          ];
        }
        return [];
      },
      loga(a: any) {
        console.log(a);
      },
      showDialog() {
        show_dialog.value = true;

        let client = GlobalData.getInstance().getCurrentClient();
        if (client) {
          let url = new URL(client.url);
          url.port =
            GlobalData.getInstance().applicationConfig?.httpserver_port ??
            HttpProtocol.DefaultHttpPort.toString();
          url.pathname = HttpProtocol.RequestUploadFile;
          url.protocol = "http:";
          url.searchParams.append("type", HttpProtocol.UploadTypeRootFS);
          upload_url_rootfs.value = url.toString();

          url.searchParams.set("type", HttpProtocol.UploadTypeSoftware);
          upload_url_software.value = url.toString();
        }
      },
      resetData() {
        loading.value = false;
        upload_url_software.value = "";
        upload_url_rootfs.value = "";
        file_count.value = 0;
      },
      async onSubmit() {
        if (file_count.value <= 0) {
          $q.notify({
            type: "warning",
            message: $t.t("please select file first") + "!",
            position: "top",
            timeout: 1500,
          });
          return;
        }
        loading.value = true;
        try {
          let upgrader =
            upgrade_type.value == $t.t("software")
              ? uploader_software.value
              : uploader_rootfs.value;
          $q.dialog({
            title: $t.t("Confirm"),
            message: $t.t("use this file to upgrade") + "?",
            cancel: true,
            persistent: true,
          })
            .onOk(() => {
              upgrader.upload();
            })
            .onCancel(() => {
              loading.value = false;
              loading.value = false;
            });
        } catch {}
      },
      onUploaded() {
        loading.value = false;
        let upgrader =
          upgrade_type.value == $t.t("software")
            ? uploader_software.value
            : uploader_rootfs.value;
        if (upgrader) {
          console.log(upgrader);
          upgrader.removeUploadedFiles();
        }
        $q.notify({
          type: "positive",
          icon: "done",
          message:
            $t.t("update file upload") +
            $t.t("success") +
            "! \n" +
            upgrade_type.value +
            $t.t("automatically restarts after the upgrade is complete"),
          position: "top",
          timeout: 1500,
        });
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      },
      onFailed(info: any) {
        $q.notify({
          type: "warning",
          message: $t.t("update file upload") + $t.t("fail") + "!",
          position: "top",
          timeout: 1500,
        });
        loading.value = false;
      },
    };
  },
});
</script>
