<template>
  <v-expansion-panel v-if="available()">
    <v-expansion-panel-header
      disable-icon-rotate
      expand-icon="$ayiFileDownload"
      >{{ $ay.t("Export") }}</v-expansion-panel-header
    >
    <v-expansion-panel-content>
      <v-radio-group v-model="exportFormat">
        <v-radio label="JSON" value="json"></v-radio>
        <v-radio label="CSV" value="csv"></v-radio>
      </v-radio-group>

      <v-btn icon @click="goHelp()"><v-icon>$ayiQuestionCircle</v-icon></v-btn>
      <v-btn color="blue darken-1" text @click="doAction()">{{
        $ay.t("Export")
      }}</v-btn>
    </v-expansion-panel-content>
  </v-expansion-panel>
</template>
<script>
export default {
  data: () => ({
    exportFormat: "json",
    jobActive: false
  }),
  methods: {
    available() {
      return (
        this.dataListSelection.AType != 0 &&
        this.dataListSelection.AType != window.$gz.type.PartInventoryRestock
      );
    },
    goHelp() {
      window.open(this.$store.state.helpUrl + "ay-ex-export", "_blank");
    },

    async doAction() {
      //do the export and trigger download
      let vm = this;
      let url = `export/render/${vm.exportFormat}`;
      let body = this.dataListSelection;

      try {
        //call api route
        let res = await window.$gz.api.upsert(url, body);
        if (res.error) {
          //Error object constructor must be a string
          throw new Error(window.$gz.errorHandler.errorToString(res, vm));
        }

        let href = window.$gz.api.genericDownloadUrl(
          "export/download/" + res.data
        );
        if (window.open(href, "DownloadExport") == null) {
          throw new Error(
            "Unable to download, your browser rejected navigating to download url."
          );
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
        window.$gz.eventBus.$emit("notify-error", vm.$ay.t("JobFailed"));
      }
    }
  },
  props: {
    dataListSelection: { type: Object, default: null }
  }
};
</script>
