<template>
  <v-row v-if="formState.ready">
    <v-col dense>
      <v-form ref="form">
        <!-- Prevent implicit submission of the form on enter key, this is not necessary on a form with a text area which is why I never noticed it with the other forms -->
        <button
          type="submit"
          disabled
          style="display: none"
          aria-hidden="true"
        ></button>
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <v-select
              v-model="templateId"
              dense
              :items="selectLists.pickListTemplates"
              item-text="name"
              item-value="id"
              :label="$ay.t('PickListTemplates')"
              data-cy="selectTemplate"
              :disabled="formState.dirty"
              @input="templateSelected"
            >
            </v-select>
          </v-col>
          <template v-for="(item, index) in workingArray">
            <v-col :key="item.key" cols="12" sm="6" lg="4" xl="2" px-2>
              <v-card>
                <v-card-title>
                  {{ item.title }}
                </v-card-title>
                <v-card-subtitle>
                  {{ item.key }}
                </v-card-subtitle>
                <v-card-text>
                  <v-checkbox
                    :ref="item.key"
                    v-model="item.include"
                    dense
                    :readonly="formState.readOnly"
                    :label="$ay.t('Include')"
                    :disabled="item.required"
                    :data-cy="item.key + 'Include'"
                    @change="includeChanged(item)"
                  ></v-checkbox>
                  <!-- RE-ORDER CONTROL -->
                  <div class="d-flex justify-space-between">
                    <v-btn icon @click="move('start', index)"
                      ><v-icon>$ayiStepBackward</v-icon></v-btn
                    >
                    <v-btn icon @click="move('left', index)"
                      ><v-icon>$ayiBackward</v-icon></v-btn
                    >
                    <v-btn icon @click="move('right', index)"
                      ><v-icon>$ayiForward</v-icon></v-btn
                    >
                    <v-btn icon @click="move('end', index)"
                      ><v-icon>$ayiStepForward</v-icon></v-btn
                    >
                  </div>
                </v-card-text>
              </v-card>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
//
//NOTE: This is a simple form with no need for business rules or validation so stripped out any extraneous code related to all that
//
const FORM_KEY = "adm-global-select-templates";
const API_BASE_URL = "pick-list/template/";
export default {
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  data() {
    return {
      obj: {
        id: null,
        concurrency: null,
        template: null
      },
      selectLists: {
        pickListTemplates: []
      },
      availableFields: [],
      workingArray: [],
      fieldKeys: [],
      templateId: 0,
      lastFetchedTemplateId: 0,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.getRights(window.$gz.type.FormCustom)
    };
  }, //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    },
    templateId(val) {
      if (val) {
        window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":delete");
      } else {
        window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":delete");
      }
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.formState.ready = true;
      vm.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: this would normally be in getDataFromAPI but this form doesn't really need that function so doing it here
      generateMenu(vm);
      //init disable save button so it can be enabled only on edit to show dirty form
      window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
      window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":delete");
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  methods: {
    includeChanged: function() {
      window.$gz.form.setFormState({
        vm: this,
        dirty: true
      });
    },
    move: function(direction, index) {
      const totalItems = this.workingArray.length;
      let newIndex = 0;
      //calculate new index
      switch (direction) {
        case "start":
          newIndex = 0;
          break;
        case "left":
          newIndex = index - 1;
          if (newIndex < 0) {
            newIndex = 0;
          }
          break;
        case "right":
          newIndex = index + 1;
          if (newIndex > totalItems - 1) {
            newIndex = totalItems - 1;
          }

          break;
        case "end":
          newIndex = totalItems - 1;
          break;
      }

      this.workingArray.splice(
        newIndex,
        0,
        this.workingArray.splice(index, 1)[0]
      );
      window.$gz.form.setFormState({
        vm: this,
        dirty: true
      });
    },
    templateSelected: function() {
      const vm = this;
      if (vm.lastFetchedTemplateId == vm.templateId) {
        return; //no change
      }
      vm.workingArray = [];
      if (!vm.templateId || vm.templateId == 0) {
        vm.lastFetchedTemplateId = 0;
        return;
      } else {
        vm.getDataFromApi();
      }
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      if (!vm.templateId || vm.templateId == 0) {
        return;
      }
      vm.lastFetchedTemplateId = vm.templateId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(
          API_BASE_URL + "listfields/" + vm.templateId
        );

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.availableFields = res.data;
          vm.fieldKeys = [];
          for (let i = 0; i < res.data.length; i++) {
            vm.fieldKeys.push(res.data[i].tKey);
          }
          await window.$gz.translation.cacheTranslations(vm.fieldKeys);
        }
        //get current edited template
        res = await window.$gz.api.get(API_BASE_URL + vm.templateId);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          synthesizeWorkingArray(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      window.$gz.form.deleteAllErrorBoxErrors(this);
      //Create template data object here....
      //Note that server expects to see a string array of json template, not actual json
      const newObj = {
        id: this.templateId,
        template: "[]"
      };
      //temporary array to hold template for later stringification
      const temp = [];
      for (let i = 0; i < this.workingArray.length; i++) {
        const ti = this.workingArray[i];
        if (ti.include == true) {
          temp.push({
            fld: ti.key
          });
        }
      }
      try {
        //now set the template as a json string
        newObj.template = JSON.stringify(temp);
        const res = await window.$gz.api.upsert(API_BASE_URL, newObj);
        this.formState.loading = false;
        if (res.error) {
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          //It's a 204 no data response so no error means it's ok
          //form is now clean
          window.$gz.form.setFormState({
            vm: this,
            dirty: false
          });
        }
      } catch (error) {
        this.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, this);
      }
    },
    async remove() {
      if (
        (await window.$gz.dialog.confirmGeneric(
          "ResetToDefault",
          "warning"
        )) !== true
      ) {
        return;
      }
      try {
        this.formState.loading = true;
        if (this.templateId && this.templateId != 0) {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.templateId
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            //trigger reload of form
            this.getDataFromApi();
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: null,
    title: "PickListTemplates",
    helpUrl: "adm-global-autocomplete-templates",
    formData: {
      ayaType: window.$gz.type.FormCustom,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });

    if (vm.rights.delete) {
      menuOptions.menuItems.push({
        title: "ResetToDefault",
        icon: "$ayiUndo",
        surface: false,
        key: FORM_KEY + ":delete",
        vm: vm
      });
    }
  }

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

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  await populateSelectionLists(vm);
}

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

//////////////////////
//
//
async function populateSelectionLists(vm) {
  const res = await window.$gz.api.get(API_BASE_URL + "list");
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
  } else {
    res.data.sort(window.$gz.util.sortByKey("name"));
    vm.selectLists.pickListTemplates = res.data;
    window.$gz.form.addNoSelectionItem(vm.selectLists.pickListTemplates);
  }
}

////////////////////
//
function synthesizeWorkingArray(vm) {
  vm.workingArray = [];
  if (vm.obj.template == null) {
    return;
  }
  const template = JSON.parse(vm.obj.template);
  //first, insert the templated fields into the working array so they are in current selected order
  for (let i = 0; i < template.length; i++) {
    const templateItem = template[i];
    const afItem = vm.availableFields.find(z => z.fieldKey == templateItem.fld);
    if (afItem != null) {
      //Push into working array
      vm.workingArray.push({
        key: afItem.fieldKey,
        required: afItem.isRowId == true,
        include: true,
        title: vm.$ay.t(afItem.tKey)
      });
    }
  }

  //Now iterate all the available fields and insert the ones that were not in the current template
  for (let i = 0; i < vm.availableFields.length; i++) {
    const afItem = vm.availableFields[i];
    //skip the active column
    if (afItem.isActiveColumn == true) {
      continue;
    }
    //is this field already in the template and was added above?
    if (template.find(z => z.fld == afItem.fieldKey) != null) {
      continue;
    }
    //Push into working array
    vm.workingArray.push({
      key: afItem.fieldKey,
      required: afItem.isRowId == true,
      include: false,
      title: vm.$ay.t(afItem.tKey)
    });
  }
}
</script>
