///Add data key names which make the custom fields control work more easily
///Since the names can be inferred from the data that comes from the server it saves bandwidth to do it here at the client
function addDataKeyNames(obj) {
  //iterate the array of objects
  //if it has a "type" property then it's a custom field so add its data key name

  for (let i = 0; i < obj.length; i++) {
    if (obj[i].type) {
      obj[i]["dataKey"] = "c" + parseInt(obj[i].fld.replace(/^\D+/g, ""));
    }
  }

  //return the whole thing again now translated
  return obj;
}

export default {
  ////////////////////////////////
  // Cache the form customization data if it's not already present
  // NOTE: FORM KEY **MUST** BE THE AYATYPE NAME WHERE POSSIBLE, IF NO TYPE THEN AN EXCEPTION NEEDS TO BE CODED IN
  //SERVER FormFieldReference.cs -> public static List<string> FormFieldKeys
  //
  async get(formKey, vm, forceRefresh) {
    if (
      forceRefresh ||
      !window.$gz.util.has(window.$gz.store.state.formCustomTemplate, formKey)
    ) {
      //fetch and populate the store
      const res = await window.$gz.api.get("form-custom/" + formKey);
      if (res.error) {
        throw new Error(window.$gz.errorHandler.errorToString(res, vm));
      }

      window.$gz.store.commit("setFormCustomTemplateItem", {
        formKey: formKey,
        concurrency: res.data.concurrency,
        value: addDataKeyNames(JSON.parse(res.data.template))
      });
    }
  },
  set(formKey, token, template) {
    window.$gz.store.commit("setFormCustomTemplateItem", {
      formKey: formKey,
      concurrency: token,
      value: addDataKeyNames(JSON.parse(template))
    });
  },
  getFieldTemplateValue(formKey, fieldKey) {
    if (fieldKey === undefined) {
      throw new Error(
        "ERROR form-custom-template::getFieldTemplateValue -> fieldKey not specified for template for form [" +
          formKey +
          "]"
      );
    }

    const template = window.$gz.store.state.formCustomTemplate[formKey];
    if (template === undefined) {
      throw new Error(
        "ERROR form-custom-template::getFieldTemplateValue -> Store is missing form template for [" +
          formKey +
          "]"
      );
    }

    //Note that not every field being requested will exist so it's valid to return undefined
    //template is an array of objects that contain a key called "fld"
    return template.find(z => z.fld == fieldKey);
  },
  getTemplateConcurrencyToken(formKey) {
    const tok =
      window.$gz.store.state.formCustomTemplate[formKey + "_concurrencyToken"];
    if (tok === undefined) {
      throw new Error(
        "ERROR form-custom-template::getTemplateConcurrencyToken -> Store is missing concurrency token for [" +
          formKey +
          "]"
      );
    }

    return tok;
  }
};
