<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-11 text-h6">
              {{ $t("background image") }}
            </div>
            <div class="col-1">
              <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-uploader
                  class="full-width"
                  ref="uploader"
                  :url="upload_url"
                  method="post"
                  :headers="generatorFileUploadHeaders"
                  :label="$t('select background image') + ':'"
                  accept="image/*"
                  :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="left">
          <q-btn
            flat
            :loading="loading"
            color="primary"
            @click="showBackgroundImage"
            :label="$t('view current background image')"
          />
          <q-space />
          <q-btn
            :loading="loading"
            flat
            :label="$t('Cancel')"
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            :loading="loading"
            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";
import { api as viewerApi } from "v-viewer";

export default defineComponent({
  name: "ComponentBackgroundImageDialog",

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

    let show_dialog = ref(false);
    let uploader: any = ref(null);
    let loading = ref(false);
    let upload_url = ref("");
    let file_count = ref(0);

    return {
      show_dialog,
      loading,
      upload_url,
      uploader,
      file_count,
      loga(a: any) {
        console.log(a);
      },
      generatorFileUploadHeaders(files: File[]) {
        if (files.length > 0) {
          return [
            {
              name: HttpProtocol.kHeaderXProductName,
              value: HttpProtocol.kHeaderDefaultValueXProductName,
            },
            {
              name: HttpProtocol.kHeaderXFileLength,
              value: files[0].size,
            },
          ];
        }
        return [];
      },
      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.UploadTypeBackgroundImage
          );
          upload_url.value = url.toString();
        }
      },
      resetData() {
        loading.value = false;
        upload_url.value = "";
        file_count.value = 0;
      },
      showBackgroundImage() {
        const temp_port =
          GlobalData.getInstance().applicationConfig?.httpserver_port ??
          HttpProtocol.DefaultHttpPort.toString();
        try {
          const url = new URL(
            GlobalData.getInstance().getCurrentClient()?.url ??
              "http://127.0.0.1:" + temp_port
          );
          url.protocol = "http";
          url.port = temp_port.toString();
          url.pathname = "/static/background_image.png";
          viewerApi({
            options: {
              toolbar: true,
              url: "data-source",
              initialViewIndex: 0,
            },
            images: [
              {
                src: url.toString(),
                "data-source": url.toString(),
              },
            ],
          });
        } catch {}
      },
      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 {
          $q.dialog({
            title: $t.t("Confirm"),
            message: $t.t("use this image to background image") + "?",
            cancel: true,
            persistent: true,
          })
            .onOk(() => {
              uploader.value.upload();
            })
            .onCancel(() => {
              loading.value = false;
            });
        } catch {}
      },
      onUploaded() {
        $q.notify({
          type: "positive",
          message: $t.t("upload background image") + $t.t("success") + "!",
          position: "top",
          timeout: 1500,
        });
        loading.value = false;
        show_dialog.value = false;
      },
      onFailed(info: any) {
        console.log(info);
        $q.notify({
          type: "warning",
          message: $t.t("upload background image") + $t.t("fail") + "!",
          position: "top",
          timeout: 1500,
        });
        loading.value = false;
      },
    };
  },
});
</script>
