const async = require('async');
const utils = require('../utils');
const basePath = process.cwd();

module.exports = (section, meta, callback) => {

  // Task flow control
  async.parallel([

    // Run processors for top level page
    async.apply(runProcessor, section, meta),

    // Run processors for children
    (cb) => async.map(section.children, (section, cb) => {
      runProcessor(section, meta, cb)
    }, cb)

  ], done);

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

}

function runProcessor(page, meta, cb) {

  if (page.processor) {
    var key = Object.keys(page.processor)[0];

    // load processor and pass in configuration
    require(`swanky-${key}`)(page, meta, cb);

  } else {
    cb(null);
  }
}