<template>
  <v-dialog
    v-model="isVisible"
    max-width="600px"
    data-cy="dataTableFilterManagerControl"
    @keydown.esc="close()"
  >
    <v-card>
      <v-card-title>{{ $sock.t("Filter") }} </v-card-title>
      <v-card-subtitle class="mt-1"
        >{{ activeFilterNameAtOpen }} {{ activeFilterCreator }}</v-card-subtitle
      >
      <v-card-text>
        <v-text-field
          v-model="activeFilter.name"
          :readonly="formState.readOnly"
          :label="$sock.t('GridFilterName')"
          required
        ></v-text-field>
        <v-checkbox
          ref="public"
          v-model="activeFilter.public"
          :readonly="formState.readOnly"
          :label="$sock.t('AnyUser')"
          data-cy="public"
        ></v-checkbox>
      </v-card-text>
      <v-card-actions>
        <v-btn text color="primary" @click="close()">{{
          $sock.t("Cancel")
        }}</v-btn>
        <v-spacer />
        <template v-if="isSelfOwned">
          <v-btn text color="primary" @click="deleteFilter()">{{
            $sock.t("Delete")
          }}</v-btn>
          <v-spacer />
        </template>

        <v-btn text color="primary" @click="saveAndExit(true)">{{
          $sock.t("SaveACopy")
        }}</v-btn>

        <template v-if="activeFilter.defaultFilter == false && isSelfOwned">
          <v-spacer />
          <v-btn text color="primary" @click="saveAndExit()">{{
            $sock.t("Save")
          }}</v-btn>
        </template>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
<script>
export default {
  components: {},
  props: {
    dataListKey: { type: String, default: null },
    activeFilterId: { type: Number, default: null }
  },
  data: () => ({
    isVisible: false,
    resolve: null,
    reject: null,
    activeFilter: {
      id: 0,
      userId: 0,
      name: null,
      public: false,
      defaultFilter: true,
      listKey: null,
      filter: "[]"
    },
    activeFilterNameAtOpen: null,
    activeFilterCreator: "",
    isSelfOwned: true,
    formState: {
      ready: false,
      dirty: false,
      valid: true,
      readOnly: false,
      loading: true,
      errorBoxMessage: undefined,
      appError: undefined,
      serverError: {}
    }
  }),
  async created() {
    await initForm(this);
  },
  methods: {
    async deleteFilter() {
      //prompt if a true delete and not a default filter "reset"
      if (!this.activeFilter.defaultFilter) {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
      }

      const res = await window.$gz.api.remove(
        `data-list-filter/${this.activeFilter.id}`
      );
      if (res.error) {
        throw new Error(window.$gz.errorHandler.errorToString(res, this));
      } else {
        this.close({ refresh: true });
      }
    },
    async saveAndExit(saveAs) {
      if (saveAs) {
        //SAVE AS
        //strip ID
        delete this.activeFilter.id;
        delete this.activeFilter.concurrency;

        //save as can never save as default
        this.activeFilter.defaultFilter = false;
        //save as can never be same name as default -
        if (
          this.activeFilter.name == "-" ||
          this.activeFilter.name == this.activeFilterNameAtOpen
        ) {
          this.activeFilter.name += " [" + this.$sock.t("Copy") + "]";
        }
        this.activeFilter.userId = window.$gz.store.state.userId;
        const res = await window.$gz.api.post(
          "data-list-filter",
          this.activeFilter
        );
        if (res.error) {
          throw new Error(window.$gz.errorHandler.errorToString(res, this));
        } else {
          this.close({ refresh: true, newFilterId: res.data.id });
        }
      } else {
        //SAVE
        const res = await window.$gz.api.put(
          "data-list-filter",
          this.activeFilter
        );
        if (res.error) {
          throw new Error(window.$gz.errorHandler.errorToString(res, this));
        } else {
          this.close({ refresh: true });
        }
      }
    },
    async open(tableColumnData) {
      this.tableColumnData = tableColumnData;

      await fetchActiveFilter(this);
      this.activeFilterNameAtOpen = this.activeFilter.name;
      this.isSelfOwned =
        this.activeFilter.userId == window.$gz.store.state.userId;

      //Get owner name
      if (!this.isSelfOwned) {
        const res = await window.$gz.api.post("pick-list/list", {
          sockType: window.$gz.type.User,
          inactive: true,
          preselectedIds: [this.activeFilter.userId]
        });

        if (res.error) {
          this.activeFilterCreator = " (creator: UNKNOWN / ERROR)";
          throw new Error(window.$gz.errorHandler.errorToString(res, this));
        } else {
          this.activeFilterCreator = `(${res.data[0].name})`;
        }
      }

      this.isVisible = true;
      return new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
    },
    close(ret) {
      this.isVisible = false;

      this.resolve(ret);
    }
  }
};
/////////////////////////////////
//
//
async function initForm() {
  await fetchTranslatedText();
}

////////////////////
//
async function fetchActiveFilter(vm) {
  ///api/v8/data-list-filter/{id}
  const res = await window.$gz.api.get(`data-list-filter/${vm.activeFilterId}`);
  if (res.error) {
    throw new Error(window.$gz.errorHandler.errorToString(res, vm));
  } else {
    vm.activeFilter = res.data;
  }
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations(["GridFilterName", "AnyUser"]);
}
</script>
