#!/usr/bin/env node
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = download;

var _process = _interopRequireDefault(require("process"));

var _functions = require("../functions");

var _functions2 = require("./functions");

var _utils = require("../utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Download courses/nanodegrees and save them locally
 * @param {array} courseIds list of course ids to download
 * @param {string} targetDir target directory to save downloaded courses/Nanodegrees
 */
async function download(courseIds, targetDir) {
  try {
    const token = await (0, _functions.retrieveUdacityAuthToken)();

    for (let i = 0, len = courseIds.length; i < len; i += 1) {
      const courseId = courseIds[i];
      let isNanodegree = false; // check if this is a course or Nanodegree

      if (courseId.startsWith('nd')) {
        isNanodegree = true;
      }

      if (isNanodegree) {
        await (0, _functions2.downloadNanodegree)(courseId, targetDir, token);
      } else {
        await (0, _functions2.downloadCourse)(courseId, targetDir, token);
      }
    }
  } catch (error) {
    const errorMsg = (0, _utils.getFullErrorMessage)(error);

    _utils.logger.error(`Failed to download course. See error below:\n${errorMsg}`);

    _process.default.exit(1);
  }
}