const async = require('async');
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');

module.exports = (navigation, section, config, callback) => {

  // Task flow control
  async.parallel([

    // Compile top level page
    async.apply(compilePage, section),

    // Compile children if required
    (cb) => async.map(section.children, compilePage, cb)

  ], done);

  // On complete handler
  function done(err, result) {
    if (err) {
      callback(err);
    } else {
      callback(null, section)
    }
  }

  function compilePage(page, cb) {

    // Determine first page in Sections object
    if(page.key === navigation[0].key) {
      page.filename = 'index.html';
      page.path = 'index.html';
    }

    // Post process html css classes
    page.contentCompiled = page.contentCompiled.map((content) => {
      return ejs.render(content, { styles: config.meta.cssMap }, { cache: false });
    });

    // Compile main page
    var data = {
      key: page.key,
      parentKey: page.parentKey,
      siteTitle: page.meta.title,
      title: page.title,
      contents: page.contentCompiled,
      nav: navigation,
      styles: config.meta.cssMap
    };

    var options = {
      filename: page.layoutSrc,
      cache: true
    };

    fs.readFile(page.layoutSrc, 'utf-8', (err, str) => {
      page.compiled = ejs.compile(str, options)(data);
      cb();
    });

  };
}
