"use strict";

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

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

var _ora = _interopRequireDefault(require("ora"));

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 Nanodegree from Udacity API
 * @param {string} ndKey Nanodegree key
 * @param {string} targetDir target directory to save downloaded Nanodegree
 * @param {string} udacityAuthToken Udacity authentication token
 */
async function downloadNanodegree(ndKey, targetDir, udacityAuthToken) {
  _utils.logger.info(`Start downloading Nanodegree ${ndKey} from Udacity API`);

  let dirNd;
  let dirNdName;
  let ndJSON;
  let titleNd;
  const spinner = (0, _ora.default)(`Get Nanodegree ${ndKey} information`).start();

  try {
    // validate if user is authorized to download this Nanodegree
    // and check which version to download
    const nanodegreeRes = await (0, _.retrieveUserNanodegreeInfo)(ndKey, udacityAuthToken);

    if (!nanodegreeRes) {
      spinner.fail();

      const _error = new Error(`Fail to find Nanodegree key ${ndKey} in your profile. The key ${ndKey} either doesn't exist or you don't have access to it.`);

      throw _error;
    }

    spinner.succeed();
    const {
      key,
      locale,
      version
    } = nanodegreeRes;

    _utils.logger.info(`You're authorized to download version ${version}, locale ${locale} of Nanodegree ${key}`);

    const res = await (0, _api.fetchNanodegree)({
      key,
      locale,
      version
    }, udacityAuthToken);
    ndJSON = res;
    const {
      nanodegree
    } = res.data;
    titleNd = nanodegree.title; // create folder for Nanoderee

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

    const shouldProceed = await (0, _.checkOverwriteDir)(targetDir, dirNdName);
    if (!shouldProceed) return; // TODO: check

    dirNd = (0, _utils.makeDir)(targetDir, dirNdName); // save Nanodegree JSON to file

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

    _fs.default.writeFileSync(file, jsonStr); // loop through parts, modules, lessons to create folder
    // and download lessons


    await (0, _.downloadParts)(nanodegree.parts, ndKey, dirNd, udacityAuthToken);

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

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