import {
  ascend,
  filter,
  find,
  head,
  last,
  prop,
  propEq,
  sortBy,
  values,
} from 'ramda';

/**
 * Image source url selected based on provided prop width
 * out of filtered list of sources based on aspect ratio
 * @param {number} width - Value of default width.
 * @param {Object} filteredSizes - List of images sizes to look through.
 * @returns {String} path to the image size that matches
 */
const getImageUrlByWidth = (width, filteredSizes) => {
  const sizesArray = values(filteredSizes);

  const sizeUrlByWidth = prop(
    'source_url',
    find(propEq('width', width), sizesArray)
  );

  // Uses the image that is the same size as width by default
  if (sizeUrlByWidth) {
    return sizeUrlByWidth;
  }

  // Filters available images widths to the ones bigger than width
  // Sorts the larger widths in descending order and picks the smallest
  const largestSizeUrl = last(
    sortBy(
      ascend(prop('width')),
      filter(
        (size) => prop('width', size) > width,
        sizesArray
      )
    )
  );

  // Uses the image next largest closest to the width
  // if exact width image is not there
  if (largestSizeUrl) {
    return prop('source_url', largestSizeUrl);
  }

  // Filters available images widths to the ones smaller than width
  // Sorts the smaller widths in descending order and picks the biggest
  const smallestSizeUrl = head(
    sortBy(
      ascend(prop('width')),
      filter(
        (size) => prop('width', size) < width,
        sizesArray
      )
    )
  );

  // Uses the image next smallest closest to the width
  // if exact width image is not there
  if (smallestSizeUrl) {
    return prop('source_url', smallestSizeUrl);
  }

  // Returns undefined if no image can be found
  return undefined;
};

export default getImageUrlByWidth;
