"use strict";

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

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

var _path = _interopRequireDefault(require("path"));

var _ = require(".");

var _sidebar = require("./sidebar");

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

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

/**
 * Iterate through lessons to trigger writing HTML files for concepts,
 * project descriptions, rubrics, etc.
 * @param {string} jsonPath directory path to look for json file
 * @param {string} targetDir output directory
 * @param {function} doneModule callback function of module loop
 */
async function writeHtmlLesson(jsonPath, targetDir) {
  const pathData = _path.default.join(jsonPath, 'data.json');

  const pathRubric = _path.default.join(jsonPath, 'rubric.json'); // Delete all existing html files in the lesson folder if any
  // This is to make sure when the cli is updated and the new file
  // structure is different, no outdated files created from the previous cli
  // version remains.


  (0, _utils.deleteFilesInFolder)(targetDir, 'html'); // read json file for data

  let data = _fs.default.readFileSync(pathData, 'utf-8');

  data = JSON.parse(data);
  data = data.data.lesson;
  const {
    concepts,
    lab,
    project
  } = data; // try to get rubric data first if available

  const promiseRubric = new Promise(resolve => {
    _fs.default.access(pathRubric, _fs.default.constants.F_OK, error => {
      if (error) {
        // there are no rubric.json to parse
        resolve();
        return;
      }

      _fs.default.readFile(pathRubric, 'utf-8', (errorReadFile, rubric) => {
        if (errorReadFile) {
          throw error;
        }

        rubric = JSON.parse(rubric);
        data.rubric = rubric;
        resolve();
      });
    }); //.fs.access rubric

  }); //.promise

  try {
    await promiseRubric;
    const promises = await Promise.all([(0, _sidebar.createHtmlSidebarLesson)(data), (0, _.writeHtmlLessonSummary)(data, targetDir)]);
    const htmlSidebar = promises[0];

    for (let i = 0, len = concepts.length; i < len; i += 1) {
      const conceptIndex = i + 1;
      const nextConcept = i === len - 1 ? null : concepts[i + 1];
      await (0, _.writeHtmlConcept)(concepts[i], nextConcept, htmlSidebar, targetDir, conceptIndex);
    }

    let promiseWriteHtmlRubric;

    if (data.rubric) {
      promiseWriteHtmlRubric = (0, _.writeHtmlRubric)(data.rubric, project, htmlSidebar, targetDir);
    }

    await promiseWriteHtmlRubric;
    await (0, _.writeHtmlProjectDescription)(project, htmlSidebar, targetDir);
    await (0, _.writeHtmlLab)(lab, htmlSidebar, targetDir);
  } catch (error) {
    throw error;
  }
}