import {
  concat,
  map,
  mergeRight,
  prop,
  startsWith,
  values,
} from 'ramda';

/**
   * Computes the setup object needed by Jwplayer
   * @param {Object} jwPlayerConfig - App specific set up preference.
   * @param {Object} videoMedium - The video object to get.
   * @param {string} fallbackAspectRatio - Aspect ratio to use if none in video.
   * @returns {Object} setup object required by jwplayer
   */
const getJwplayerSetup = (
  jwPlayerConfig,
  videoMedium,
  fallbackAspectRatio
) => {
  const {
    id,
    endpoints,
    playback,
  } = videoMedium;

  let tracks = [{
    file: endpoints.preview_thumbnails,
    kind: 'thumbnails',
  }];

  // A check for video subtitles because not all videos have one
  if (endpoints.subtitles) {
    const subtitles = map(
      (subtitle) => ({
        file: subtitle,
        kind: 'captions',
        label: 'Default subtitles',
      }),
      values(endpoints.subtitles)
    );
    tracks = concat(tracks, subtitles);
  }

  // A check for video chapters because not all videos have one
  if (endpoints.chapter_timestamps) {
    tracks = concat(tracks, [{
      file: endpoints.chapter_timestamps,
      kind: 'chapters',
    }]);
  }

  // Offline support- if there is a valid offline url, we use it
  // If not, we use HTTP Live streaming version
  const sources = startsWith('file', endpoints.offline)
    ? [{ file: endpoints.offline, type: 'mp4' }]
    : [{ file: endpoints.hls, type: 'hls' }];

  // Playlist required by jwplayer to play video
  const playlist = [{
    mediaid: id,
    tracks,
    sources,
  }];

  // Gets aspect ratio from video or uses fallback fallbackAspectRatio
  const mediumAspectRatio
    = prop('aspect_ratio', playback) || fallbackAspectRatio;

  const defaultSetup = {
    playlist,
    aspectratio: mediumAspectRatio,
  };

  // Combines the setup we make with the one passed down from parent component
  return mergeRight(defaultSetup, jwPlayerConfig);
};

export default getJwplayerSetup;
