<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <span class="title">{{ $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"
              :disabled="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"
              :disabled="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"
              :disabled="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-row>
        <v-row>
          <v-col cols="12" class="mt-6">
            <v-col cols="12" lg="4">
              <span class="title">{{ $ay.t("BackupFiles") }}</span>
              <v-btn @click="getBackupStatus" class="ml-3">
                <v-icon>fa-sync</v-icon>
              </v-btn>

              <v-simple-table>
                <template v-slot:default>
                  <thead>
                    <tr>
                      <th class="text-left">{{ $ay.t("FileName") }}</th>
                      <th class="text-left">{{ $ay.t("FileDate") }}</th>
                      <th class="text-left">{{ $ay.t("FileSize") }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="item in backupFileList" :key="item.id">
                      <td>
                        <template v-if="!formState.readOnly">
                          <a :href="item.url">{{ item.name }}</a>
                        </template>
                        <template v-else>
                          {{ item.name }}
                        </template>
                      </td>
                      <td>{{ item.created }}</td>
                      <td>{{ item.length }}</td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-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 {
  created() {
    let vm = this;
    initForm(vm)
      .then(() => {
        vm.rights = window.$gz.role.getRights(window.$gz.type.GlobalOps);
        vm.formState.readOnly = !vm.rights.change;
        vm.formState.ready = true;
        window.$gz.eventBus.$on("menu-click", clickHandler);
        vm.getDataFromApi();
        vm.getBackupStatus();
      })
      .catch(err => {
        vm.formState.ready = true;
        window.$gz.errorHandler.handleFormError(err, vm);
      });
  },
  beforeRouteLeave(to, from, next) {
    if (this.formState.dirty) {
      window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
        if (dialogResult == true) {
          next();
        } else {
          next(false);
        }
      });
    } else {
      next();
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: null,
      backupFileList: [],
      backupAvailableSpace: null,
      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.getBrowserTimeZoneName(),
      languageName: window.$gz.locale.getBrowserLanguages(),
      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);
      }
    },
    getBackupStatus() {
      let vm = this;
      //  vm.formState.loading = true;
      let url = "backup/status";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      window.$gz.api
        .get(url)
        .then(res => {
          if (res.error) {
            if (res.error.code == "2010") {
              window.$gz.eventBus.$emit(
                "notify-error",
                vm.$ay.t("ErrorAPI2010")
              );
              window.$gz._.delay(function() {
                vm.$router.go(-1);
              }, 2000);
            }
            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(function handleGetBackupFileListError(error) {
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
          window.$gz.errorHandler.handleFormError(error, vm);
        });
    },
    getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      let url = "global-ops-backup-setting";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      window.$gz.api
        .get(url)
        .then(res => {
          if (res.error) {
            if (res.error.code == "2010") {
              window.$gz.eventBus.$emit(
                "notify-error",
                vm.$ay.t("ErrorAPI2010")
              );
              window.$gz._.delay(function() {
                vm.$router.go(-1);
              }, 2000);
            }
            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(function handleGetDataFromAPIError(error) {
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
          window.$gz.errorHandler.handleFormError(error, vm);
        });
    },
    submit() {
      let vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;
        let url = "global-ops-backup-setting";
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        window.$gz.api
          .upsert(url, vm.obj)
          .then(res => {
            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(function handleSubmitError(error) {
            vm.formState.loading = false;
            window.$gz.errorHandler.handleFormError(error, vm);
          });
      }
    },
    backupNow() {
      let vm = this;
      vm.formState.loading = true;
      let url = "backup/backup-now";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      window.$gz.api
        .upsert(url, {})
        .then(res => {
          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          }
        })
        .catch(function handleSubmitError(error) {
          vm.formState.loading = false;
          window.$gz.errorHandler.handleFormError(error, vm);
        });
    }
  }
};

/////////////////////////////
//
//
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":
        window.$gz.dialog
          .confirmGeneric("AreYouSureBackupNow")
          .then(dialogResult => {
            if (dialogResult == 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,
    icon: "fa-file-archive",
    title: vm.$ay.t("Backup"),
    helpUrl: "form-ops-backup",
    hideSearch: true,
    formData: {},
    menuItems: []
  };

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

    menuOptions.menuItems.push({
      title: vm.$ay.t("BackupNow"),
      icon: "fa-file-archive",
      surface: false,
      key: FORM_KEY + ":backupnow",
      vm: vm
    });
  }

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

/////////////////////////////////
//
//
function initForm(vm) {
  return new Promise(function(resolve, reject) {
    (async function() {
      try {
        await fetchTranslatedText(vm);
      } catch (err) {
        reject(err);
      }
      resolve();
    })();
  });
}

//////////////////////////////////////////////////////////
//
//
function fetchTranslatedText(vm) {
  return window.$gz.translation.fetch([
    "BackupSettings",
    "BackupTime",
    "BackupLast",
    "BackupSetsToKeep",
    "BackupAttachments",
    "BackupFiles",
    "BackupNow",
    "AreYouSureBackupNow",
    "FileName",
    "FileSize",
    "FileDate",
    "AvailableSpace"
  ]);
}
</script>
