/*
    (c) 2010 Geraud Boyer
    Adapted from rhino.js from Douglas Crockford  (www.JSLint.com)
*/
// This is the node companion to fulljslint.js.

/*global JSLINT */
/*jslint rhino: false, strict: false */
/*global require,sys,__filename,process */

(function (args) {
    var sys = require('sys'),
        fs = require('fs'),
        path = require('path'),
        JSLINT = fs.readFileSync(path.join(path.dirname(__filename), 'fulljslint.js')).toString('UTF8'),
        options = {
            rhino: true, passfail: false, bitwise: true,
            eqeqeq: true, immed: true, newcap: true,
            nomen: true, onevar: true, plusplus: true,
            regexp: true, undef: true, white: true
        },
        filename, input;

    if (args.length === 0) {
        sys.puts('Usage: jslint.js [options] file.js');
        process.exit(1);
    }
    eval(JSLINT);

    args.forEach(function (arg, index) {
        // sys.debug("Arg(" + index + "): " + arg);
        if (arg.match(/^--no-(\w+)$/)) {
            // sys.debug("a=false");
            options[RegExp.$1] = false;
        }
        else if (arg.match(/^--(\w+)=(\S.*)$/)) {
            // sys.debug("a=b");
            // sys.debug("value: " + RegExp.$2);
            options[RegExp.$1] = JSON.parse(RegExp.$2);
        }
        else if (arg.match(/^--(\w+)$/)) {
            // sys.debug("a=true");
            options[RegExp.$1] = true;
        }
        else {
            filename = arg;
            input = fs.readFileSync(filename);
            if (!input) {
                sys.puts("jslint: Couldn't open file '" + filename + "'.");
                process.exit(1);
            }
            else {
                // sys.debug('opening input');
                input = input.toString('UTF8');
            }
        }
    });
    if (!JSLINT(input, options)) {
        JSLINT.errors.forEach(function (error) {
            if (error) {
                sys.puts('Lint at line ' + error.line + ' character ' + error.character + ': ' + error.reason);
                sys.puts((error.evidence || '').replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
                sys.puts('');
            }
        });
        process.exit(2);
    }
    else {
        sys.puts("jslint: No problems found in " + args[0]);
        process.exit(0);
    }
}(process.ARGV.slice(2)));