import { apply, divide, filter } from 'ramda';

import { printError } from '../../lib';
import { ASPECT_RATIO_FORMAT } from '../../lib/customPropTypes';

/**
 * Relative error threshold for images
 * @returns {number}
 */
const THRESHOLD = 0.05;

/**
 * Predicate to reject image sizes with a large relative error in aspect ratio
 * @param {Object} mediaSizes - List of image sizes to compare.
 * @param {string} aspectRatio - Ratio to compare by.
 * @returns {Object} Image sizes that fit into the range of the aspect ratio
 */
const filterSizesByAspectRatio = (mediaSizes = {}, aspectRatio) => {
  if (!ASPECT_RATIO_FORMAT.test(aspectRatio)) {
    printError('Invalid aspect ratio provided.');
    return {};
  }

  const aspectRatioNumeric = apply(divide, aspectRatio.split(':'));

  return filter(({ height, width }) => {
    const absoluteError = Math.abs(aspectRatioNumeric - (width / height));
    const relativeError = absoluteError / aspectRatioNumeric;

    return relativeError < THRESHOLD;
  }, mediaSizes);
};

export default filterSizesByAspectRatio;
