"use strict";

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

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

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

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

var _ = require(".");

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

/**
 * Download lesson JSON data and save it locally
 * @param {object} lesson lesson JSON data from Nanodegree JSON
 * @param {string} root_key Nanodegree key
 * @param {string} targetDir target directory to save JSON file
 * @param {string} token Udacity authentication token
 */
async function downloadLesson(lesson, rootKey, targetDir, token) {
  const {
    id,
    locale,
    project
  } = lesson; // if lesson contains a project, flag to Project Rubric

  let shouldDownloadRubric = false;

  if (project) {
    shouldDownloadRubric = true;
  }

  try {
    const res = await (0, _api.fetchLesson)({
      id,
      locale,
      rootKey
    }, token);
    const jsonStr = JSON.stringify(res, null, 2);
    const file = `${targetDir}/data.json`; // save JSON file

    _fs.default.writeFileSync(file, jsonStr);

    _utils.logger.info(`Downloaded lesson JSON for ${targetDir}`);

    if (!shouldDownloadRubric) return null; // download Project rubric

    return (0, _.downloadProjectRubric)(project, targetDir, token);
  } catch (error) {
    throw error;
  }
}