(function() {
    console.log('Building gear-lib for the browser');

    var fs = require('fs'),
        path = require('path'),
        gear = require(path.join(process.cwd(), 'node_modules/gear')),
        handlebars = require(path.join(process.cwd(), 'node_modules/handlebars')),
        LINT_CONFIG = {
            nomen: true,
            sloppy: true,
            white: true,
            vars: true
        },
        WRAP = handlebars.compile(
            "\n\ndefine('{{name}}', ['require', 'exports'{{#modules}}, '{{.}}'{{/modules}}], function(require, exports{{#input}}, {{.}}{{/input}}) {\n\n" +
            "{{{result}}}\n\n" +
            "});\n\n"
        ),
        EXPORTS = handlebars.compile(
            "define('gear-lib', ['require', 'exports'{{#tasks}}, '{{.}}'{{/tasks}}], function(require, exports) {\n" +
            "var tasks = [];\n" +
            "{{#tasks}}tasks.push(require('{{.}}'));{{/tasks}}\n" +
            "tasks.forEach(function(mod) {for (var task in mod) {exports[task] = mod[task];}});\n" +
            "});\n\n"
        ),
        DEPENDENCIES = fs.readdirSync('vendor').filter(function(f) {
                return f[0] !== '.';
            }).map(function(f) {
                return 'vendor/' + f;
            }),
        LIB = {
            'lib/csslint.js': {name: 'gear-csslint', modules: ['csslint']},
            'lib/cssminify.js': {name: 'cssminify', modules: ['less']},
            'lib/jslint.js': {name: 'gear-jslint', modules: ['jslint/lib/linter']},
            'lib/jshint.js': {name: 'gear-jshint', modules: ['jshint']},
            'lib/jsminify.js': {name: 'jsminify', modules: ['uglify-js']},
            'lib/handlebars.js': {name: 'gear-handlebars', modules: ['handlebars']}
        },
        TASKS = Object.keys(LIB).map(function(f) {return LIB[f].name;});

    return {
        deps:  {task: ['read', DEPENDENCIES]},

        tasks: {task: ['read', Object.keys(LIB)]},
        lint:  {task: ['jslint', {config: LINT_CONFIG, callback: function(blob) {
            if (blob.jslint.length) {
                console.log(blob.jslint);
            }
        }}], requires: 'tasks'},

        inline: {task: ['load', EXPORTS({tasks: TASKS})], requires: ['deps', 'lint']},
        concat: {task: ['concat', {callback: function(blob) {
            if (blob.name in LIB) {
                var obj = LIB[blob.name];
                var vars = {result: blob.result, modules: []};
                Object.keys(obj).forEach(function(attr) {vars[attr] = obj[attr];});
                return WRAP(vars);
            }
            return blob.result;
        }}], requires: 'inline'},

        dev:     {task: ['write', 'build/gear-lib.js'], requires: 'concat'},

        prodmin: {task: 'jsminify', requires: 'concat'},
        prod:    {task: ['write', 'build/gear-lib.min.js'], requires: 'prodmin'},

        join:    {requires: ['dev', 'prod']}
    };
})()
