#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    util = require('util');

var cssunminifier = require('cssunminifier');
var args = process.argv.slice(1);
var options = {};

args = args.filter(function (arg) {
    var match;

    if ((match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=([^\s]+))?$/i))) { arg = match[1]; }
    else { return arg; }

    switch (arg) {
      case 'v':
      case 'version':
        util.puts('cssunminifier ' + cssunminifier.version.join('.') + ' (CSS Unminifier) [JavaScript]');
        process.exit(0);
      case 'h':
      case 'help':
        var info = [
            'the width can be any integer >= 0',
            'to read from stdin, specify source as "-"'
        ];
        util.puts('usage: cssunminifier [-w=TAB_WIDTH] source [destination]\n\n ' + info.join('\n ') + '\n');
        process.exit(0);
      case 'w':
      case 'width':
        var width = match[2];
        width = /^\d+$/.test(width) ? parseInt(width) : -1;
        if (width > -1) options.width = width;
        break;
    }
});

var input = args[1];
if (input && input[0] != '/' && input != '-') {
    input = path.join(process.cwd(), input);
}
var output = args[2];
if (output && output[0] != '/') {
    output = path.join(process.cwd(), output);
}

var code, fd;

if (! input) {
    util.puts('cssunminifier: no input files');
    process.exit(1);
}

var parseMinifiedCSS = function (e, data) {
    if (e) {
        util.puts('lessc: ' + e.message);
        process.exit(1);
    }

    code = cssunminifier.unminify(data, options.width);

    if (output) {
        fd = fs.openSync(output, 'w');
        fs.writeSync(fd, code, 0, 'utf8');
    } else {
        util.print(code);
    }
};

if (input != '-') {
    fs.readFile(input, 'utf8', parseMinifiedCSS);
} else {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    var buffer = '';
    process.stdin.on('data', function(data) {
        buffer += data;
    });

    process.stdin.on('end', function() {
        parseMinifiedCSS(false, buffer);
    });
}
