"use strict";

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

var _fs = _interopRequireDefault(require("fs"));

var _api = require("../../../api");

var _ = require(".");

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

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

/**
 * Download JSON data of a course from Udacity API
 * @param {string} courseId course id
 * @param {string} targetDir target directory to save downloaded course JSON
 * @param {string} udacityAuthToken Udacity authentication token
 */
async function downloadCourse(courseId, targetDir, udacityAuthToken) {
  try {
    const courseJSON = await (0, _api.fetchCourse)({
      key: courseId
    }, udacityAuthToken);
    const {
      course
    } = courseJSON.data;
    const {
      lessons
    } = course;
    const titleCourse = course.title; // create folder for course

    const dirCourseName = (0, _utils.filenamify)(`${course.title} v${course.version}`); // check if folder already exist and warn the user

    const shouldProceed = await (0, _.checkOverwriteDir)(targetDir, dirCourseName);
    if (!shouldProceed) return;
    const dirCourse = (0, _utils.makeDir)(targetDir, dirCourseName); // save course JSON to file

    const jsonStr = JSON.stringify(courseJSON, null, 2);
    const file = `${dirCourse}/data.json`;

    _fs.default.writeFileSync(file, jsonStr);

    await (0, _.downloadLessons)(lessons, courseId, dirCourse, udacityAuthToken);

    _utils.logger.info(`Completed downloading ${titleCourse} course's JSON data from Udacity API`);

    _utils.logger.info('____________________\n');
  } catch (error) {
    throw error;
  }
}