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

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

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

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

              <v-data-table
                dense
                :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: $sock.t('Sort') }"
                data-cy="backupTable"
                :item-class="itemRowClasses"
                :no-data-text="$sock.t('NoData')"
              >
                <template v-slot:[`item.actions`]="{ item }">
                  <v-icon
                    v-if="item.url"
                    small
                    class="mr-6"
                    @click="deleteItem(item)"
                  >
                    $sockiTrashAlt
                  </v-icon>

                  <v-btn v-if="item.url" icon :href="item.url">
                    <v-icon small>
                      $sockiFileDownload
                    </v-icon>
                  </v-btn>
                </template></v-data-table
              >
              <div class="mt-6">
                ({{ $sock.t("AvailableSpace") }}&nbsp;{{
                  backupAvailableSpace
                }})
              </div>
            </v-col>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-backup";
export default {
  components: {},
  data() {
    return {
      formCustomTemplateKey: null,
      backupFileList: [],
      backupAvailableSpace: null,
      headers: [],
      obj: {
        id: 1,
        concurrency: 0,
        backupTime: null,
        backupSetsToKeep: 1,
        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()
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    //case 4203
    subscriptionMode() {
      return window.$gz.store.state.globalSettings.sBuild;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const 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
    }
  },
  async created() {
    const 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);
  },

  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) {
      const vm = this;
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        vm.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const 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() {
      const vm = this;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get("backup/status");
        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;
            const ret = [];
            for (let i = 0; i < res.data.backupFiles.length; i++) {
              const 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() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get("global-ops-backup-setting");
        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() {
      const vm = this;
      try {
        if (vm.canSave) {
          vm.formState.loading = true;

          window.$gz.form.deleteAllErrorBoxErrors(vm);
          //case 4203
          //always 1 if a subscription
          if (this.subscriptionMode) {
            vm.obj.backupSetsToKeep = 1;
          }
          const res = await window.$gz.api.upsert(
            "global-ops-backup-setting",
            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() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.upsert("backup/backup-now", {});
        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);
      }
    },
    itemRowClasses: function(item) {
      let ret = "";

      if (item.length == "0 B") {
        ret += this.form().tableRowErrorClass();
      }
      return ret;
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const 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) {
  const menuOptions = {
    isMain: true,
    readOnly: vm.formState.readOnly,
    icon: "$sockiFileArchive",
    title: "Backup",
    helpUrl: "ops-form-backup",
    formData: {
      sockType: window.$gz.type.Backup
    },
    menuItems: []
  };

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

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

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

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

//////////////////////////////////////////////////////////
//
//
async function fetchTranslatedText() {
  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.$sock.t("FileName"),
      align: "start",
      value: "name"
    },
    { text: vm.$sock.t("FileDate"), value: "created" },
    { text: vm.$sock.t("FileSize"), value: "length" },
    { text: "", value: "actions", sortable: false }
  ];
}
</script>
