<template>
  <v-row v-if="formState.ready" dense>
    <v-col>
      <v-form ref="form" data-cy="customizeForm">
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>

          <template v-for="item in obj">
            <v-col :key="item.key" cols="12" sm="6" lg="4" xl="2" px-2>
              <v-card :data-cy="item.key">
                <v-card-title>
                  {{ item.title }}
                </v-card-title>
                <v-card-subtitle>
                  {{ item.tKey }}
                </v-card-subtitle>
                <v-card-text>
                  <v-checkbox
                    v-if="item.hideable"
                    :ref="item.key"
                    v-model="item.visible"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('FormFieldVisible')"
                    :disabled="formState.readOnly"
                    :data-cy="item.key + 'Visible'"
                    @change="visibleChanged(item)"
                  ></v-checkbox>
                  <v-checkbox
                    v-if="!requiredDisabled(item)"
                    v-model="item.required"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('FormFieldEntryRequired')"
                    :disabled="requiredDisabled(item) || formState.readOnly"
                    @change="requiredChanged(item)"
                  ></v-checkbox>
                  <v-select
                    v-if="item.custom"
                    v-model="item.type"
                    dense
                    :readonly="formState.readOnly"
                    :items="selectLists.uiFieldDataTypes"
                    item-text="name"
                    item-value="id"
                    :label="$sock.t('UiFieldDataType')"
                    :data-cy="item.key + 'SelectType'"
                    @input="dataTypeChanged(item)"
                  ></v-select>
                  <!-- <v-divider></v-divider>
                  <div>{{ item }}</div> -->
                </v-card-text>
              </v-card>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
//
//  CUSTOMIZE A FORM'S FIELDS
//
const FORM_KEY = "customize";
const API_BASE_URL = "form-custom/";
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: [],
      concurrency: undefined,
      formCustomTemplateKey: this.$route.params.formCustomTemplateKey,
      selectLists: {
        uiFieldDataTypes: []
      },
      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)
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);

      vm.formState.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");
    } catch (err) {
      window.$gz.errorHandler.handleFormError(err, vm);
    } finally {
      vm.formState.ready = true;
      vm.formState.loading = false;
    }
  },
  methods: {
    visibleChanged: function(item) {
      //Note: stock items can't be changed so no need to take that into account
      if (item.required && item.visible == false) {
        item.required = false;
      }
      this.formState.dirty = true;
    },
    requiredChanged: function(item) {
      //Note: stock items can't be changed so no need to take that into account
      if (item.required && item.visible == false) {
        item.visible = true;
      }
      this.formState.dirty = true;
    },
    requiredDisabled: function(item) {
      if (
        !item.requireable ||
        item.key == "Wiki" ||
        item.key == "Attachments"
      ) {
        return true;
      }
      return false;
    },
    dataTypeChanged: function() {
      //nothing to scan here just set form dirty
      this.formState.dirty = true;
    },
    async submit() {
      this.formState.loading = true;
      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 = {
        formKey: this.formCustomTemplateKey,
        concurrency: this.concurrency,
        template: "[]"
      };
      //temporary array to hold template for later stringification
      const temp = [];
      //Rules:
      for (let i = 0; i < this.obj.length; i++) {
        const fldItem = this.obj[i];
        if (fldItem.custom == false) {
          //Process regular stock field
          //If it's set to hidden or required then it's template-worthy
          if (fldItem.visible == false || fldItem.required == true) {
            temp.push({
              fld: fldItem.key,
              required: fldItem.required,
              hide: !fldItem.visible
            });
          }
        } else {
          //Process custom field
          //If it's not visible then don't add it at all
          if (fldItem.visible == true) {
            temp.push({
              fld: fldItem.key,
              tKey: fldItem.tKey,
              required: fldItem.required,
              type: fldItem.type
            });
          }
        }
      }
      try {
        //now set the template as a json string
        newObj.template = JSON.stringify(temp);
        const res = await window.$gz.api.upsert(
          API_BASE_URL + this.formCustomTemplateKey,
          newObj
        );
        if (res.error) {
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          // (there is no POST of a new record for this particular object)

          //Set store values for template and token
          //(update our local cached copy of the form customizations)
          window.$gz.formCustomTemplate.set(
            this.formCustomTemplateKey,
            res.data.concurrency,
            newObj.template
          );
          //set our local concurrency token value
          this.concurrency = res.data.concurrency;

          //form is now clean
          window.$gz.form.setFormState({
            vm: this,
            dirty: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        this.formState.loading = false;
      }
    },
    hideAll() {
      for (let i = 0; i < this.obj.length; i++) {
        this.obj[i].visible = false;
      }
      this.formState.dirty = true;
    }
  }
};

/////////////////////////////
//
//
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 "DEVHIDEALL":
        m.vm.hideAll();
        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: "$sockiCustomize",
    title: "Customize",
    helpUrl: "sock-customize",
    formData: {
      sockType: window.$gz.type.FormCustom,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };

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

  //Extra link to it here so people can stumble their way onto it
  //plus it's related to this form and people think Customize for the whole shebang
  menuOptions.menuItems.push({
    title: "Translation",
    icon: "$sockiLanguage",
    data: "adm-translations",
    key: "app:nav"
  });

  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  //NOTE: This form expects to arrive here from the form being customized
  //so it does *not* attempt to fetch the translations for the field names of the form in question
  //since they should already be set by that form.
  await window.$gz.translation.cacheTranslations([
    "FormFieldEntryRequired",
    "FormFieldVisible",
    "UiFieldDataType",
    "UiFieldDataTypesCurrency",
    "UiFieldDataTypesDateOnly",
    "UiFieldDataTypesDateTime",
    "UiFieldDataTypesDecimal",
    "UiFieldDataTypesInteger",
    "UiFieldDataTypesText",
    "UiFieldDataTypesTimeOnly",
    "UiFieldDataTypesTrueFalse"
  ]);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.uiFieldDataTypes.push(
    ...[
      { name: vm.$sock.t("UiFieldDataTypesDateTime"), id: 1 },
      { name: vm.$sock.t("UiFieldDataTypesDateOnly"), id: 2 },
      { name: vm.$sock.t("UiFieldDataTypesTimeOnly"), id: 3 },
      { name: vm.$sock.t("UiFieldDataTypesText"), id: 4 },
      { name: vm.$sock.t("UiFieldDataTypesTrueFalse"), id: 6 },
      { name: vm.$sock.t("UiFieldDataTypesInteger"), id: 5 },
      { name: vm.$sock.t("UiFieldDataTypesDecimal"), id: 7 },
      { name: vm.$sock.t("UiFieldDataTypesCurrency"), id: 8 }
    ]
  );
}

////////////////////
//
function ensureTemplateIsInStore(vm) {
  //Pre-cache if necessary the form customization settings that have been set before now
  return window.$gz.formCustomTemplate.get(
    vm.$route.params.formCustomTemplateKey,
    vm,
    true
  );
}

////////////////////
//
async function initDataObject(vm) {
  //Get all the fields *available* to this form (all the fields for the object defined in AyaFormFieldDefinitions.cs as SERVER)
  //Note: this is not the actual customization data, just the list of fields that could be customized (or not if required mandatory)
  const res = await window.$gz.api.get(
    "form-field-reference/" + vm.$route.params.formCustomTemplateKey
  );
  if (res.error) {
    throw new Error(window.$gz.errorHandler.errorToString(res, vm));
  }
  //set vm.obj to the combined synthesized snapshot array of template and availble fields for working data for this form
  //	- {key, ltdisplay, custom, required, hide, type}
  //Iterate ObjectFields
  //create a new object based on the f.a.f. item and any existing template values for that item

  //Iterate first  to ensure the cached translations of field keys
  //(due to this form being opened directly from things like record history so might not be cached yet)
  //if they *are* cached then this is a pretty fast operation and no trip is made to the server
  const requiredTranslations = [];
  for (let i = 0; i < res.data.length; i++) {
    if (
      requiredTranslations.indexOf(res.data[i].tKey) === -1 &&
      res.data[i].tKey != "Wiki"
    ) {
      requiredTranslations.push(res.data[i].tKey);
    }
    //sections
    if (res.data[i].tKeySection != null) {
      if (requiredTranslations.indexOf(res.data[i].tKeySection) === -1) {
        requiredTranslations.push(res.data[i].tKeySection);
      }
    }
  }
  await window.$gz.translation.cacheTranslations(requiredTranslations);
  //Iterate a second time to build the working collection
  for (let i = 0; i < res.data.length; i++) {
    //get the formAvailableField record into an object to save typing
    const faf = res.data[i];
    //get the customTemplate record for this field if it exists
    let templateItem = window.$gz.formCustomTemplate.getFieldTemplateValue(
      vm.formCustomTemplateKey,
      faf.fieldKey
    );
    //handle non-existent template item (expected)
    if (templateItem == null) {
      templateItem = {
        required: false,
        hide: faf.isCustomField ? true : false, //hide if custom because it's not set to display if it's not present, all others are stock fields
        type: 4 //text
      };
    }
    const objItem = {
      key: faf.fieldKey,
      tKey: faf.tKey,
      title: null,
      custom: faf.isCustomField,
      required: templateItem.required === true,
      visible: templateItem.hide !== true,
      type: templateItem.type,
      hideable: faf.hideable,
      requireable: faf.requireable
    };
    //set title including optional section prepended
    if (faf.tKeySection != null) {
      objItem.title = vm.$sock.t(faf.tKeySection) + "." + vm.$sock.t(faf.tKey);
    } else {
      objItem.title = vm.$sock.t(faf.tKey);
    }
    vm.obj.push(objItem);
    vm.concurrency = window.$gz.formCustomTemplate.getTemplateConcurrencyToken(
      vm.formCustomTemplateKey
    );
  }
}
</script>
