<template>
  <div>
    <v-row>
      <gz-error :error-box-message="formState.errorBoxMessage" />
      <v-col cols="12">
        <gz-data-table
          v-if="!jobActive"
          form-key="adm-attachments"
          data-list-key="AttachmentDataList"
          :show-select="true"
          :single-select="false"
          :reload="reload"
          data-cy="attachTable"
          @selection-change="handleSelected"
        />

        <template v-if="jobActive">
          <v-progress-circular indeterminate color="primary" :size="60" />
        </template>
      </v-col>
    </v-row>
    <v-row dense justify="center">
      <v-dialog v-model="moveDialog" persistent max-width="600px">
        <v-card>
          <v-card-title>
            <span class="text-h5">{{ $sock.t("MoveSelected") }}</span>
          </v-card-title>
          <v-card-text>
            <v-select
              v-model="moveType"
              dense
              :items="selectLists.objectTypes"
              item-text="name"
              item-value="id"
              :label="$sock.t('SockType')"
            />

            <gz-pick-list
              v-if="moveType != 0"
              v-model="moveId"
              :aya-type="moveType"
              :show-edit-icon="false"
              :include-inactive="true"
              label="Id"
            />
          </v-card-text>
          <v-card-actions>
            <v-spacer />
            <v-btn color="blue darken-1" text @click="moveDialog = false">
              {{ $sock.t("Cancel") }}
            </v-btn>
            <v-btn color="blue darken-1" text @click="moveSelected()">
              {{ $sock.t("OK") }}
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>
<script>
const FORM_KEY = "adm-attachments";
export default {
  data() {
    return {
      jobActive: false,
      reload: false,
      moveDialog: false,
      moveType: null,
      moveId: null,
      selectedItems: [],
      rights: window.$gz.role.defaultRightsObject(),
      selectLists: {
        objectTypes: []
      },
      formState: {
        ready: true,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: false,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  async created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.FileAttachment);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    await fetchTranslatedText(this);
    await populateSelectionLists(this);
    generateMenu(this);
    this.handleSelected([]); //start out read only no selection state for batch ops options
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    canBatchOp() {
      return (
        this.rights.change &&
        this.selectedItems &&
        this.selectedItems.length > 0
      );
    },
    handleSelected(selected) {
      this.selectedItems = selected;

      if (this.canBatchOp()) {
        window.$gz.eventBus.$emit(
          "menu-enable-item",
          FORM_KEY + ":DELETE_SELECTED"
        );
        window.$gz.eventBus.$emit(
          "menu-enable-item",
          FORM_KEY + ":MOVE_SELECTED"
        );
      } else {
        window.$gz.eventBus.$emit(
          "menu-disable-item",
          FORM_KEY + ":DELETE_SELECTED"
        );
        window.$gz.eventBus.$emit(
          "menu-disable-item",
          FORM_KEY + ":MOVE_SELECTED"
        );
      }
    },
    async moveSelected() {
      const vm = this;
      try {
        vm.moveDialog = false;
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.upsert("attachment/batch-move", {
          idList: this.selectedItems,
          toType: this.moveType,
          toId: this.moveId
        });
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        }
        this.reload = !this.reload;
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      }
    },
    async deleteSelected() {
      const vm = this;
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.upsert(
          "attachment/batch-delete",
          this.selectedItems
        );
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        }
        this.reload = !this.reload;
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      }
    },
    async startMaintenanceJob() {
      const vm = this;
      try {
        //warning about job exclusivity
        const dialogResult = await window.$gz.dialog.confirmGeneric(
          "JobExclusiveWarning",
          "warning"
        );
        if (dialogResult == false) {
          return;
        }

        let jobId = await window.$gz.api.upsert("attachment/maintenance");
        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, vm));
        }
        jobId = jobId.jobId;
        vm.jobActive = true;
        let jobStatus = 1;
        while (vm.jobActive == true) {
          await window.$gz.util.sleepAsync(1000);
          //check if done
          jobStatus = await window.$gz.api.get(
            `job-operations/status/${jobId}`
          );
          if (jobStatus.error) {
            throw new Error(
              window.$gz.errorHandler.errorToString(jobStatus, vm)
            );
          }
          jobStatus = jobStatus.data;
          if (jobStatus == 4 || jobStatus == 0) {
            throw new Error("Job failed");
          }
          if (jobStatus == 3) {
            vm.jobActive = false;
          }
        }
        window.$gz.eventBus.$emit("notify-success", vm.$sock.t("JobCompleted"));
        this.reload = !this.reload;
      } catch (error) {
        vm.jobActive = false;
        window.$gz.errorHandler.handleFormError(error, vm);
        window.$gz.eventBus.$emit("notify-error", vm.$sock.t("JobFailed"));
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "START_MAINTENANCE_JOB":
        m.vm.startMaintenanceJob();
        break;
      case "MOVE_SELECTED":
        m.vm.moveDialog = true;

        break;
      case "DELETE_SELECTED":
        m.vm.deleteSelected();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$sockiPaperclip",
    title: "Attachments",
    helpUrl: "adm-attachments",
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "StartAttachmentMaintenanceJob",
      icon: "$sockiRobot",
      surface: false,
      key: FORM_KEY + ":START_MAINTENANCE_JOB",
      vm: vm
    });

    menuOptions.menuItems.push({
      title: "MoveSelected",
      icon: "$sockiExchangeAlt",
      surface: false,
      key: FORM_KEY + ":MOVE_SELECTED",
      vm: vm
    });

    menuOptions.menuItems.push({
      title: "DeleteSelected",
      icon: "$sockiTrashAlt",
      surface: false,
      key: FORM_KEY + ":DELETE_SELECTED",
      vm: vm
    });
  }

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "StartAttachmentMaintenanceJob",
    "JobExclusiveWarning",
    "DeleteSelected",
    "MoveSelected"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  const res = await window.$gz.api.get("enum-list/list/coreall");
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
  } else {
    vm.selectLists.objectTypes = res.data;
    window.$gz.form.addNoSelectionItem(vm.selectLists.objectTypes);
  }
}
</script>
