<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <span class="text-h6">{{ $ay.t("BackupSettings") }}</span>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-time-picker
              :label="$ay.t('BackupTime')"
              :rules="[form().required(this, 'backupTime')]"
              :error-messages="form().serverErrors(this, 'backupTime')"
              v-model="obj.backupTime"
              :readonly="formState.readOnly"
              ref="backupTime"
              @input="fieldValueChanged('backupTime')"
            ></gz-time-picker>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.backupAttachments"
              :readonly="formState.readOnly"
              :label="$ay.t('BackupAttachments')"
              ref="backupAttachments"
              :error-messages="form().serverErrors(this, 'backupAttachments')"
              @change="fieldValueChanged('backupAttachments')"
            ></v-checkbox>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.backupSetsToKeep"
              :readonly="formState.readOnly"
              :label="$ay.t('BackupSetsToKeep')"
              ref="backupSetsToKeep"
              :rules="[form().integerValid(this, 'backupSetsToKeep')]"
              :error-messages="form().serverErrors(this, 'backupSetsToKeep')"
              @input="fieldValueChanged('backupSetsToKeep')"
              type="number"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.active"
              :readonly="formState.readOnly"
              :label="$ay.t('Active')"
              ref="active"
              :error-messages="form().serverErrors(this, 'active')"
              @change="fieldValueChanged('active')"
            ></v-checkbox>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12" class="mt-6">
            <v-col cols="12">
              <span class="text-h6">{{ $ay.t("BackupFiles") }}</span>
              <v-btn @click="getBackupStatus" class="mb-6">
                <v-icon>$ayiSync</v-icon>
              </v-btn>

              <v-data-table
                :headers="headers"
                :items="backupFileList"
                class="elevation-1"
                :disable-pagination="true"
                :disable-filtering="true"
                hide-default-footer
                :sort-by="['created']"
                :sort-desc="[true]"
                :header-props="{ sortByText: $ay.t('Sort') }"
                data-cy="backupTable"
                :no-data-text="$ay.t('NoData')"
              >
                <template v-slot:[`item.actions`]="{ item }">
                  <v-icon small class="mr-6" @click="deleteItem(item)">
                    $ayiTrashAlt
                  </v-icon>

                  <v-btn icon :href="item.url" v-if="item.url">
                    <v-icon small>
                      $ayiFileDownload
                    </v-icon>
                  </v-btn>
                </template></v-data-table
              >
              <div class="mt-6">
                ({{ $ay.t("AvailableSpace") }}&nbsp;{{ backupAvailableSpace }})
              </div>
            </v-col>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "ops-backup";

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(window.$gz.type.Backup);
      vm.formState.readOnly = !vm.rights.change;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
      vm.getBackupStatus();
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: null,
      backupFileList: [],
      backupAvailableSpace: null,
      headers: [],
      obj: {
        id: 1,
        concurrency: 0,
        backupTime: null,
        backupSetsToKeep: null,
        backupAttachments: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject(),
      //cache display format stuff
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        let canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async deleteItem(item) {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        //do the delete
        vm.formState.loading = true;

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let res = await window.$gz.api.remove(`backup/${item.name}`);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //refresh
          await vm.getBackupStatus();
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        vm.formState.loading = false;
      }
    },
    async getBackupStatus() {
      let vm = this;
      //  vm.formState.loading = true;
      let url = "backup/status";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //process add url dl token and id
          if (res.data) {
            vm.backupAvailableSpace = res.data.availableFreeSpace;
            let ret = [];
            for (let i = 0; i < res.data.backupFiles.length; i++) {
              let o = res.data.backupFiles[i];
              ret.push({
                id: i,
                created: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.created,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                ),
                url: vm.formState.readOnly
                  ? null
                  : window.$gz.api.backupDownloadUrl(o.name),
                name: o.name,
                length: o.length
              });
            }
            vm.backupFileList = ret;
          } else {
            vm.backupFileList = [];
          }
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      let url = "global-ops-backup-setting";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      let vm = this;
      try {
        if (vm.canSave) {
          vm.formState.loading = true;
          let url = "global-ops-backup-setting";
          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.upsert(url, vm.obj);

          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.obj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
          }
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async backupNow() {
      let vm = this;
      vm.formState.loading = true;
      let url = "backup/backup-now";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.upsert(url, {});
        vm.formState.loading = false;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "backupnow":
        if (
          (await window.$gz.dialog.confirmGeneric(
            "AreYouSureBackupNow",
            "warning"
          )) === true
        ) {
          m.vm.backupNow();
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    readOnly: vm.formState.readOnly,
    icon: "$ayiFileArchive",
    title: "Backup",
    helpUrl: "ops-backup",
    formData: {
      ayaType: window.$gz.type.Backup
    },
    formData: {},
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });

    menuOptions.menuItems.push({
      title: "BackupNow",
      icon: "$ayiFileArchive",
      surface: false,
      key: FORM_KEY + ":backupnow",
      vm: vm
    });
  }

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

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

//////////////////////////////////////////////////////////
//
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "BackupSettings",
    "BackupTime",
    "BackupLast",
    "BackupSetsToKeep",
    "BackupAttachments",
    "BackupFiles",
    "BackupNow",
    "AreYouSureBackupNow",
    "FileName",
    "FileSize",
    "FileDate",
    "AvailableSpace"
  ]);
}

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    {
      text: vm.$ay.t("FileName"),
      align: "start",
      value: "name"
    },
    { text: vm.$ay.t("FileDate"), value: "created" },
    { text: vm.$ay.t("FileSize"), value: "length" },
    { text: "", value: "actions", sortable: false }
  ];
}
</script>
