<template>
  <v-dialog
    v-model="isVisible"
    max-width="600px"
    data-cy="dataTableFilterManagerControl"
    @keydown.esc="close()"
  >
    <v-card>
      <v-card-title>{{ $ay.t("Filter") }} </v-card-title>
      <v-card-subtitle class="mt-1"
        >{{ activeFilterNameAtOpen }} {{ activeFilterCreator }}</v-card-subtitle
      >
      <v-card-text>
        <!-- 
          TASKS:
          save a default filter to a named filter
          change and save a named filter
          overwrite a named filter with new filter selections from default filter
          
          Modes ON OPEN OF THIS DIALOG 
        
        - named saved filter was selected 
          edit: name, all users
          Options: cancel, delete, {NOTE META NOT DOING THIS SEE NO PRACTICAL REASON "Duplicate" (was 'save a copy')}, Save if name or all users changed
        
        - Default filter was selected
          edit: name, all users, replace select        
          Options: cancel, delete (resets it), ["Save As" (was 'save a copy', only if replacement selection is NOT made) | "Replace" (if replace selection made)]
           {{ activeFilter }}
        -->

        <template v-if="isDefaultFilter">
          <div v-if="selectedSavedFilterIdToOverWrite == null" class="mb-5">
            <!-- DEFAULT UN-NAMED FILTER BEING EDITED BLOCK -->
            <h2>
              {{ $ay.t("SaveAs") }}
            </h2>
            <v-text-field
              v-model="activeFilter.name"
              :readonly="formState.readOnly"
              :label="$ay.t('GridFilterName')"
              required
            ></v-text-field>

            <v-checkbox
              ref="public"
              v-model="activeFilter.public"
              :readonly="formState.readOnly"
              :label="$ay.t('AnyUser')"
              data-cy="public"
            ></v-checkbox>
          </div>
          <div v-if="offerReplace && !defaultFilterNameEdited" class="mb-5">
            <h2>{{ $ay.t("Replace") }}</h2>
            <v-select
              v-model="selectedSavedFilterIdToOverWrite"
              :items="selectLists.savedFilters"
              item-text="name"
              item-value="id"
              :label="$ay.t('DataListSavedFilter')"
            >
            </v-select>
          </div>
          <v-card-actions>
            <v-btn text color="primary" @click="close()">{{
              $ay.t("Cancel")
            }}</v-btn>
            <v-spacer />
            <template
              v-if="isSelfOwned && selectedSavedFilterIdToOverWrite == null"
            >
              <v-btn text color="primary" @click="deleteFilter()">{{
                $ay.t("Delete")
              }}</v-btn>
              <v-spacer />
            </template>

            <v-btn
              v-if="selectedSavedFilterIdToOverWrite == null"
              text
              :disabled="!defaultFilterIsSavAsAble"
              color="primary"
              @click="saveAndExit('save-as-new')"
              >{{ $ay.t("Save") }}</v-btn
            >
            <v-btn
              v-if="selectedSavedFilterIdToOverWrite != null"
              text
              color="primary"
              @click="saveAndExit('replace-column-filters')"
              >{{ $ay.t("Replace") }}</v-btn
            >
          </v-card-actions>
        </template>
        <template v-else>
          <!-- EXISTING NAMED FILTER BEING EDITED BLOCK -->
          <v-text-field
            v-model="activeFilter.name"
            :readonly="formState.readOnly"
            :label="$ay.t('GridFilterName')"
            required
          ></v-text-field>
          <v-checkbox
            ref="public"
            v-model="activeFilter.public"
            :readonly="formState.readOnly"
            :label="$ay.t('AnyUser')"
            data-cy="public"
          ></v-checkbox>
          <v-card-actions>
            <v-btn text color="primary" @click="close()">{{
              $ay.t("Cancel")
            }}</v-btn>
            <v-spacer />
            <template v-if="isSelfOwned">
              <v-btn text color="primary" @click="deleteFilter()">{{
                $ay.t("Delete")
              }}</v-btn>
              <v-spacer />
            </template>

            <v-btn
              text
              :disabled="!namedFilterIsSavable"
              color="primary"
              @click="saveAndExit('update-name-all-users')"
              >{{ $ay.t("Save") }}</v-btn
            >
          </v-card-actions>
        </template>
      </v-card-text>
    </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,
    activeFilterPublicAtOpen: null,
    activeFilterCreator: "",
    isSelfOwned: true,
    selectedSavedFilterIdToOverWrite: null,
    selectLists: {
      savedFilters: []
    },

    formState: {
      ready: false,
      dirty: false,
      valid: true,
      readOnly: false,
      loading: true,
      errorBoxMessage: undefined,
      appError: undefined,
      serverError: {}
    }
  }),
  computed: {
    offerReplace() {
      return (
        this.activeFilter.defaultFilter &&
        this.selectLists.savedFilters.length > 0
      );
    },
    isDefaultFilter() {
      if (this.activeFilter && this.activeFilter.defaultFilter) {
        return true;
      }
      return false;
    },
    namedFilterIsSavable() {
      if (
        this.activeFilter.name != this.activeFilterNameAtOpen ||
        this.activeFilter.public != this.activeFilterPublicAtOpen
      ) {
        return true;
      } else {
        return false;
      }
    },
    defaultFilterNameEdited() {
      if (this.activeFilter.name != this.activeFilterNameAtOpen) {
        return true;
      } else {
        return false;
      }
    },
    defaultFilterIsSavAsAble() {
      if (
        this.defaultFilterNameEdited &&
        this.selectedSavedFilterIdToOverWrite == null
      ) {
        return true;
      } else {
        return false;
      }
    },
    defaultFilterIsOverWriteSavAble() {
      if (this.selectedSavedFilterIdToOverWrite != null) {
        return true;
      } else {
        return false;
      }
    }
  },
  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(saveMode) {
      switch (saveMode) {
        case "save-as-new":
          {
            //create new named filter with the column filter settings and selected name and all users settings of the current
            //default filter
            //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.$ay.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 });
            }
          }
          break;
        case "replace-column-filters":
          {
            //replace existing named filter with the column filter settings (only) of the current
            //default filter

            if (this.selectedSavedFilterIdToOverWrite == null) {
              return;
            }

            //Fetch existing
            let dataFilterToBeOverwritten = await window.$gz.api.get(
              `data-list-filter/${this.selectedSavedFilterIdToOverWrite}`
            );
            if (dataFilterToBeOverwritten.error) {
              throw new Error(
                window.$gz.errorHandler.errorToString(
                  dataFilterToBeOverwritten,
                  this
                )
              );
            } else {
              dataFilterToBeOverwritten = dataFilterToBeOverwritten.data;
            }

            //overwrite filter settings
            dataFilterToBeOverwritten.filter = this.activeFilter.filter;

            //save over existing
            const res = await window.$gz.api.put(
              "data-list-filter",
              dataFilterToBeOverwritten
            );
            if (res.error) {
              throw new Error(window.$gz.errorHandler.errorToString(res, this));
            } else {
              this.close({
                refresh: true,
                newFilterId: dataFilterToBeOverwritten.id
              }); //switch to the new filter id
            }
          }
          break;
        case "update-name-all-users":
          {
            //update existing named filter with the name and / or all users settings of the current
            //default filter, column filter settings ignored / kept as is
            //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 });
            }
          }
          break;
      }
    },
    async open(tableColumnData) {
      this.tableColumnData = tableColumnData;
      this.selectedSavedFilterIdToOverWrite = null;

      await fetchActiveFilter(this);
      this.activeFilterNameAtOpen = this.activeFilter.name;
      this.activeFilterPublicAtOpen = this.activeFilter.public;
      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", {
          ayaType: 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})`;
        }
      }

      await fetchSavedFilterList(this);

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

////////////////////
//
async function fetchSavedFilterList(vm) {
  const res = await window.$gz.api.get(
    "data-list-filter/list?ListKey=" + vm.dataListKey
  );
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
  } else {
    //use previous selects but weed out default filter
    vm.selectLists.savedFilters = res.data.filter(z => z.default != true);
  }
}

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