<template>
  <div>
    <v-row>
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <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"
          @selection-change="handleSelected"
          data-cy="attachTable"
        >
        </gz-data-table>

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

            <gz-pick-list
              v-if="moveType != 0"
              :aya-type="moveType"
              :show-edit-icon="false"
              :include-inactive="true"
              v-model="moveId"
              label="Id"
            ></gz-pick-list>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="moveDialog = false">{{
              $ay.t("Cancel")
            }}</v-btn>
            <v-btn color="blue darken-1" text @click="moveSelected()">{{
              $ay.t("OK")
            }}</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<script>
const FORM_KEY = "adm-attachments";
export default {
  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);
  },
  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: {}
      }
    };
  },
  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(aType, ayId) {
      let vm = this;
      try {
        //called from move dialog, already selected
        vm.moveDialog = false;

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let 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() {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let 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() {
      let vm = this;

      try {
        //warning about job exclusivity
        let dialogResult = await window.$gz.dialog.confirmGeneric(
          "JobExclusiveWarning",
          "warning"
        );
        if (dialogResult == false) {
          return;
        }

        //call seed route
        let jobId = await window.$gz.api.upsert("attachment/maintenance");
        if (jobId.error) {
          //throw new Error(jobId.error);
          throw new Error(window.$gz.errorHandler.errorToString(jobId, vm));
        }
        jobId = jobId.jobId; //it's in a sub key
        vm.jobActive = true;

        /*  /// <summary>
    /// Job status for opsjobs
    /// </summary>
    public enum JobStatus : int
    {
        Absent=0,
        Sleeping = 1,
        Running = 2,
        Completed = 3,
        Failed = 4
    } */
        let jobStatus = 1;
        //get status

        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(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;
          }
        }

        //Here if it's completed successfully
        window.$gz.eventBus.$emit("notify-success", vm.$ay.t("JobCompleted"));
        this.reload = !this.reload;
      } catch (error) {
        vm.jobActive = false;
        window.$gz.errorHandler.handleFormError(error, vm);
        window.$gz.eventBus.$emit("notify-error", vm.$ay.t("JobFailed"));
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let 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) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiFolder",
    title: "Attachments",
    helpUrl: "adm-attachments",
    menuItems: []
  };

  //STUB REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  //get last report selected
  let lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      icon: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

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

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

    menuOptions.menuItems.push({
      title: "DeleteSelected",
      icon: "$ayiTrashAlt",
      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(vm) {
  await window.$gz.translation.cacheTranslations([
    "StartAttachmentMaintenanceJob",
    "JobExclusiveWarning",
    "DeleteSelected",
    "MoveSelected"
  ]);
}

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