import includes from 'lodash/includes';
import map from 'lodash/map';
import reduce from 'lodash/reduce';
import keys from 'lodash/keys';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';

/**
 * Helper function to provide field meta data for all formik fields defined within a yup schema
 *
 * @param {Object} schema created by the yup validation library
 * @param {Function} getFieldMeta handler provided by the useFormikContext hook
 * @returns {Object} keyed meta data from formik.getFieldMeta, plus valid state
 */
export const getFieldsMeta = (schema, getFieldMeta) => {
  const fieldKeys = keys(schema.fields);

  const reduceFields = (_fieldKeys, prefix = '') => reduce(_fieldKeys, (result, field) => {
    const fieldKey = `${prefix}${field}`;
    const nestedFields = get(schema.fields, `${fieldKey.split('.').join('.fields.')}.fields`);
    if (nestedFields) {
      // Recurse for nested field keys
      result[field] = reduceFields(keys(nestedFields), `${fieldKey}.`);
    } else {
      const fieldKey = `${prefix}${field}`;
      const fieldMeta = getFieldMeta(fieldKey);
      result[field] = {
        ...fieldMeta,
        valid: (!isEmpty(fieldMeta.value) || fieldMeta.touched) && !fieldMeta.error,
      };
    }

    return result;
  }, {});

  return reduceFields(fieldKeys);
};

/**
 * Checks array of field names and returns whether or not all are valid
 * @param {Array} fieldNames
 * @param {Object} fieldsMeta provided by forms.getFieldsMeta util
 * @returns {Boolean}
 */
export const fieldsAreValid = (fieldNames, fieldsMeta) => !includes(map(fieldNames, fieldName => get(fieldsMeta, `${fieldName}.valid`)), false);

/**
 * Returns the error state of a field in a way that's sensible for our components
 * @param {*} fieldMeta metadata for a field provided by formik's getFieldMeta
 * @returns error string or null
 */
export const getFieldError = fieldMeta => fieldMeta.touched && fieldMeta.error ? fieldMeta.error : null;

@@ -1755,17 +1755,22 @@
 @param %7B
-*
+Object
 %7D fieldM
@@ -1970,8 +1970,269 @@
 : null;%0A
+%0A/**%0A * Convert longhand version of units to a condensed version, such as Units/hour =%3E U/h%0A * @param %7BString%7D units%0A * @returns %7BString%7D condensed version of units%0A */%0Aexport const getCondensedUnits = units =%3E map(units.split('/'), part =%3E part%5B0%5D).join('/');%0A

Add util for converting long-form units strings to a condensed version