// TODO: Create a class from that file.
export default (data, keyToFind) => {
  let result = [];

  // Keep only levels with { isFruit: true }.
  JSON.stringify(data, (_, nestedValue) => {
    if (nestedValue && nestedValue[keyToFind]) {
      result.push(nestedValue);
    }
    return nestedValue;
  });

  // Check for a Fruit structure.
  result = result.filter(fruit => {
    return fruit_structure(fruit, [
      "color",
      "description",
      "expires",
      "id",
      "image",
      "isFruit",
      "name",
      "price",
      "taste"
    ]);
  });

  // Sort fruits by id.
  result.sort((a, b) => {
    return a.id - b.id;
  });

  return result;
};

/**
 * Check for a Fruit structure.
 *
 * @param {Object} obj
 * @param {Array} attrs
 */
function fruit_structure(obj, attrs) {
  // Check if a field is missing.
  for (let i = 0; i < attrs.length; ++i) {
    if (!Object.prototype.hasOwnProperty.call(obj, attrs[i])) return false;
  }

  // Check for additional fields.
  Object.fromEntries(
    // eslint-disable-next-line no-unused-vars
    Object.entries(obj).filter(([key, value]) => {
      // It mutates the initial object by reference.
      if (key === "does") delete obj[key];
      return attrs.includes(key);
    })
  );

  return true;
}
