{"size": 2005, "ext": "js", "max_stars_repo_path": "models/movies.js", "max_stars_repo_name": "belcurv/nm_fullstack_project", "max_stars_repo_stars_event_min_datetime": "2020-07-24T17:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T17:02:57.000Z", "max_issues_repo_path": "models/movies.js", "max_issues_repo_name": "belcurv/nm_fullstack_project", "max_issues_repo_issues_event_min_datetime": "2021-03-08T20:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T04:19:52.000Z", "max_forks_repo_path": "models/movies.js", "max_forks_repo_name": "belcurv/nm_fullstack_project", "max_forks_repo_forks_event_min_datetime": "2020-04-24T13:53:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-24T13:53:05.000Z"}
{"max_stars_count": 1, "max_issues_count": 6, "max_forks_count": 1, "avg_line_length": 25.0625, "max_line_length": 79, "alphanum_fraction": 0.5301745636}
'use strict';

/* ================================= SETUP ================================= */

const request   = require('request-promise-native');
const Validator = require('../utils/validator');
const validator = new Validator();
const apiUrl    = 'https://www.omdbapi.com';
const apiKey    = process.env.OMDB_API_KEY;


/* ============================ PUBLIC METHODS ============================= */

/**
 * Get one movie
 * @param    {String}   imdbID   imdbID
 * @returns  {Object}            Promise + movie
*/
const getOne = (imdbID) => {

  try {
    validator.check({ imdbID });
  } catch (err) {
    return Promise.reject(err);
  }

  const options = {
    url  : apiUrl,
    qs   : { apikey : apiKey, i : imdbID },
    json : true
  };
  return request(options);
};


/**
 * Search by title; returns no more than 50 movies at a time
 * @param    {String}   title    Movie title to search for
 * @param    {Number}   page     Optional results page number
 * @returns  {Object}            Promise + array of movies
*/
const search = async ({ title, page = 1 }) => {
  try {
    validator.check({ title, page });
  } catch (err) {
    console.log('search validator failed for', title);
    return Promise.reject(err);
  }

  const options = {
    url  : apiUrl,
    qs   : { apikey : apiKey, s : title, page },
    json : true
  };

  try {
    const response    = await request(options);
    const numResults  = +response.totalResults;
    const numRequests = numResults > 50 ? 5 : Math.floor(50 / numResults) + 1;
    const result      = response;

    if (numResults > 10) {
      for (let i = page + 1; i < numRequests + page; i += 1) {
        options.qs.page = i;
        let nextPage    = await request(options);
        result.Search.push(...nextPage.Search);
      }
    }

    return Promise.resolve(result);
  } catch (err) {
    return Promise.reject(err);
  }
};


/* ================================ EXPORTS ================================ */

module.exports = { getOne, search };
