<template>
  <v-row v-if="formState.ready">
    <v-col>
      <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>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <v-select
              v-model="templateId"
              :items="selectLists.pickListTemplates"
              item-text="name"
              item-value="id"
              :label="$ay.t('PickListTemplates')"
              @input="templateSelected"
              :data-cy="!!$ay.dev ? 'SelectTemplate' : false"
              :disabled="formState.dirty"
            >
            </v-select>
          </v-col>
          <!-- <div>WORKING ARRAY: {{ workingArray }}</div> -->

          <!-- <div>
              TEMPLATE:
              {{ obj }}
            </div>

            <div>
              available fields:
              {{ availableFields }}
            </div> -->
          <template v-for="(item, index) in workingArray">
            <v-col :key="item.key" cols="12" sm="6" lg="4" xl="3" 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
                    v-model="item.include"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Include')"
                    :ref="item.key"
                    :disabled="item.required"
                    @change="includeChanged(item)"
                    :data-cy="!!$ay.dev ? item.key + 'Include' : false"
                  ></v-checkbox>
                  <!-- RE-ORDER CONTROL -->
                  <div class="d-flex justify-space-between">
                    <v-btn large icon @click="move('start', index)"
                      ><v-icon large>fa-step-backward</v-icon></v-btn
                    >
                    <v-btn large icon @click="move('left', index)"
                      ><v-icon large>fa-backward</v-icon></v-btn
                    >
                    <v-btn large icon @click="move('right', index)"
                      ><v-icon large>fa-forward</v-icon></v-btn
                    >
                    <v-btn large icon @click="move('end', index)"
                      ><v-icon large>fa-step-forward</v-icon></v-btn
                    >
                  </div>
                </v-card-text>
              </v-card>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//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);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    let 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
      //modify the menu as necessary
      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);
    }
  },
  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) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        let 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");
      }
    }
  },
  methods: {
    includeChanged: function(item) {
      window.$gz.form.setFormState({
        vm: this,
        dirty: true
      });
    },
    move: function(direction, index) {
      let 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() {
      let 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() {
      let vm = this;
      vm.formState.loading = true;
      if (!vm.templateId || vm.templateId == 0) {
        return;
      }
      vm.lastFetchedTemplateId = vm.templateId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        //get available fields
        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);
        }

        //weirdly, this wasn't working properly until I put it in a function, it was just executing immediately before translations were resolved from fetch above
        //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);
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      let vm = this;
      let url = API_BASE_URL;
      //clear any errors vm might be around from previous submit
      window.$gz.form.deleteAllErrorBoxErrors(vm);

      //Create template data object here....
      //Note that server expects to see a string array of json template, not actual json
      let newObj = {
        id: vm.templateId,
        template: "[]"
      };
      //temporary array to hold template for later stringification
      let temp = [];
      for (let i = 0; i < vm.workingArray.length; i++) {
        let ti = vm.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);
        let res = await window.$gz.api.upsert(url, newObj);

        vm.formState.loading = false;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //It's a 204 no data response so no error means it's ok
          //form is now clean
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false
          });
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async remove() {
      let vm = this;
      if (
        (await window.$gz.dialog.confirmGeneric(
          "ResetToDefault",
          "warning"
        )) !== true
      ) {
        return;
      }
      try {
        //do the delete
        vm.formState.loading = true;
        //No need to delete a new record, just abandon it...
        if (vm.templateId && vm.templateId != 0) {
          let url = API_BASE_URL + vm.templateId;

          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.remove(url);

          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //trigger reload of form
            this.getDataFromApi();
          }
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let 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) {
  let menuOptions = {
    isMain: false,
    icon: null,
    title: "PickListTemplates",
    helpUrl: "form-adm-global-select-templates",
    formData: {
      ayaType: window.$gz.type.FormCustom,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };

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

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

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

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

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

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

////////////////////
//
function synthesizeWorkingArray(vm) {
  vm.workingArray = [];
  if (vm.obj.template == null) {
    return;
  }
  let 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++) {
    let templateItem = template[i];
    let afItem = window.$gz._.find(vm.availableFields, [
      "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++) {
    let 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 (window.$gz._.find(template, ["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>
