<template>
  <v-row v-if="formState.ready" dense>
    <v-col>
      <v-form ref="form">
        <!-- Prevent implicit submission of the form on enter key, this is not necessary on a form with a text area which is why I never noticed it with the other forms -->
        <button
          type="submit"
          disabled
          style="display: none"
          aria-hidden="true"
        ></button>
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <img
              class="grey lighten-2"
              :src="smallUrl"
              :alt="$sock.t('SmallLogo')"
            />
            <v-file-input
              v-model="uploadSmall"
              dense
              accept="image/*"
              show-size
              :label="$sock.t('SmallLogo')"
              :rules="rules"
              data-cy="uploadSmall"
            ></v-file-input>
            <v-btn color="primary" text @click="remove('small')">{{
              $sock.t("Delete")
            }}</v-btn>
            <v-btn color="primary" text @click="upload('small')">{{
              $sock.t("Upload")
            }}</v-btn>
          </v-col>
          <v-col cols="12" class="mt-10">
            <img
              class="mt-10 grey lighten-2"
              :src="mediumUrl"
              :alt="$sock.t('MediumLogo')"
            />
            <v-file-input
              v-model="uploadMedium"
              dense
              accept="image/*"
              show-size
              :label="$sock.t('MediumLogo')"
              :rules="rules"
            ></v-file-input>
            <v-btn color="primary" text @click="remove('medium')">{{
              $sock.t("Delete")
            }}</v-btn>
            <v-btn color="primary" text @click="upload('medium')">{{
              $sock.t("Upload")
            }}</v-btn>
          </v-col>
          <v-col cols="12" class="mt-10">
            <img
              class="mt-10 grey lighten-2"
              :src="largeUrl"
              :alt="$sock.t('LargeLogo')"
            />
            <v-file-input
              v-model="uploadLarge"
              dense
              accept="image/*"
              show-size
              :label="$sock.t('LargeLogo')"
              :rules="rules"
            ></v-file-input>
            <v-btn color="primary" text @click="remove('large')">{{
              $sock.t("Delete")
            }}</v-btn>
            <v-btn color="primary" text @click="upload('large')">{{
              $sock.t("Upload")
            }}</v-btn>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
//
//NOTE: This is a simple form with no need for business rules or validation so stripped out any extraneous code related to all that
//
const FORM_KEY = "adm-global-logo";
export default {
  data() {
    return {
      uploadSmall: null,
      uploadMedium: null,
      uploadLarge: null,
      mediumUrl: null,
      largeUrl: null,
      smallUrl: null,
      fileSizeExceededWarning: "",
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.getRights(window.$gz.type.Global),
      rules: [
        value => !value || value.size < 512000 || this.fileSizeExceededWarning
      ]
    };
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.formState.ready = true;
      vm.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: this would normally be in getDataFromAPI but this form doesn't really need that function so doing it here
      generateMenu(vm);
      vm.smallUrl = `${window.$gz.api.logoUrl("small")}?x=${Date.now()}`;
      vm.mediumUrl = `${window.$gz.api.logoUrl("medium")}?x=${Date.now()}`;
      vm.largeUrl = `${window.$gz.api.logoUrl("large")}?x=${Date.now()}`;
      vm.fileSizeExceededWarning = vm.$sock
        .t("AyaFileFileTooLarge")
        .replace("{0}", "512KiB");
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  methods: {
    imageUrl(size) {
      return window.$gz.api.logoUrl(size);
    },
    async upload(size) {
      //similar code in wiki-control
      const vm = this;
      let fileData = null;
      switch (size) {
        case "small":
          fileData = vm.uploadSmall;
          break;
        case "medium":
          fileData = vm.uploadMedium;
          break;
        case "large":
          fileData = vm.uploadLarge;
          break;
        default:
          return;
      }
      if (fileData == null) {
        return;
      }
      if (fileData.size > 512000) {
        window.$gz.eventBus.$emit("notify-error", vm.fileSizeExceededWarning);
        return;
      }
      try {
        const res = await window.$gz.api.uploadLogo(fileData, size);
        if (res.error) {
          window.$gz.errorHandler.handleFormError(res.error);
        } else {
          switch (size) {
            case "small":
              vm.smallUrl = `${window.$gz.api.logoUrl(size)}?x=${Date.now()}`;
              break;
            case "medium":
              vm.mediumUrl = `${window.$gz.api.logoUrl(size)}?x=${Date.now()}`;
              break;
            case "large":
              vm.largeUrl = `${window.$gz.api.logoUrl(size)}?x=${Date.now()}`;
              break;
            default:
              return;
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error);
      }
    },

    async remove(size) {
      const vm = this;

      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        const url = "logo/" + size;

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.remove(url);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          switch (size) {
            case "small":
              vm.smallUrl = null;
              break;
            case "medium":
              vm.mediumUrl = null;
              break;
            case "large":
              vm.largeUrl = null;
              break;
            default:
              return;
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: null,
    title: "GlobalLogo",
    helpUrl: "adm-global-logo",
    menuItems: []
  };
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "SmallLogo",
    "MediumLogo",
    "LargeLogo",
    "GlobalLogo",
    "AyaFileFileTooLarge"
  ]);
}
</script>
