/**
 * Get the Sites Config from Application YAML
 */
module.exports = function(gulp, taskSettings) {
    var TASK_NAME = 'appConfig',
        APP_YAML = 'application.yaml';

    function findApplicationYAMLPath() {
        var findUp = require('find-up');
        return findUp.sync(APP_YAML);
    }

    return {
        name: TASK_NAME,
        appYAMLPath: '',
        task: function getAppConfigTask(done) {
            var _subTasks = [];

            // Find Application YAML By Traversing up the folder tree
            this.appYAMLPath = findApplicationYAMLPath();
            if (this.appYAMLPath !== null) {
                var yaml = require('gulp-yaml'),
                    merge = require('merge-stream'),
                    path = require('path');
                taskSettings.PROJECT_PATH = path.dirname(this.appYAMLPath) + '/';
                _subTasks.push(
                    gulp.src(this.appYAMLPath)
                    .pipe(yaml())
                    .pipe(gulp.dest('./.tmp/'))
                );

                return merge(_subTasks);
            }

            // Return Error if Application YAML is not found
            return done(new Error('Cannot find application.yaml for the project, Please contact the team lead to ensure the project has been setup properly.'));
        }
    }
};

