// Generated by CoffeeScript 1.8.0

/*
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2014 (c) Markus Kohlhase <mail@markus-kohlhase.de>
 */

(function() {
  var addResult, async, collect, colorRegex, exts, filterFiles, fmtOpts, fmts, fs, helpers, k, list, options, p, parseFile, path, pkg, print, programm, readDir, readSingleFile, readdirp, result, sloc;

  fs = require('fs');

  path = require('path');

  async = require('async');

  programm = require('commander');

  readdirp = require('readdirp');

  sloc = require('./sloc');

  helpers = require('./helpers');

  pkg = require('../package.json');

  fmts = require('./formatters');

  list = function(val) {
    return val.split(',');
  };

  exts = (function() {
    var _i, _len, _ref, _results;
    _ref = sloc.extensions;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      k = _ref[_i];
      _results.push("*." + k);
    }
    return _results;
  })();

  collect = function(val, memo) {
    memo.push(val);
    return memo;
  };

  colorRegex = /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g;

  parseFile = function(f, cb) {
    var res;
    if (cb == null) {
      cb = function() {};
    }
    res = {
      path: f,
      stats: {},
      badFile: false
    };
    return fs.readFile(f, "utf8", function(err, code) {
      if (err) {
        res.badFile = true;
        return cb(err, res);
      }
      res.stats = sloc(code, path.extname(f).slice(1));
      return cb(null, res);
    });
  };

  print = function(err, result, opts, fmtOpts) {
    var f, fmt, out;
    if (err) {
      return console.error("Error: " + err);
    }
    f = programm.format || 'simple';
    if ((fmt = fmts[f]) == null) {
      return console.error("Error: format " + f + " is not supported");
    }
    out = fmt(result, opts, fmtOpts);
    if (programm.stripColors) {
      out = out.replace(colorRegex, '');
    }
    if (typeof out === "string") {
      return console.log(out);
    }
  };

  addResult = function(res, global) {
    if (res.badFile) {
      global.brokenFiles++;
    }
    return global.files.push(res);
  };

  filterFiles = function(files) {
    var exclude, r, res, _i, _len, _results;
    res = programm.exclude ? (exclude = new RegExp(programm.exclude), files.filter(function(x) {
      return !exclude.test(x.path);
    })) : files;
    _results = [];
    for (_i = 0, _len = res.length; _i < _len; _i++) {
      r = res[_i];
      _results.push(path.join(p, r.path));
    }
    return _results;
  };

  options = {};

  fmtOpts = [];

  programm.version(pkg.version).usage('[option] <file> | <directory>').option('-e, --exclude <regex>', 'regular expression to exclude files and folders').option('-f, --format <format>', 'format output:' + ((function() {
    var _results;
    _results = [];
    for (k in fmts) {
      _results.push(" " + k);
    }
    return _results;
  })()).join(',')).option('    --format-option [value]', 'add formatter option', collect, fmtOpts).option('    --strip-colors', 'remove all color characters').option('-k, --keys <keys>', 'report only numbers of the given keys', list).option('-d, --details', 'report stats of each analized file');

  programm.parse(process.argv);

  options.keys = programm.keys;

  options.details = programm.details;

  if (programm.args.length < 1) {
    return programm.help();
  }

  result = {
    files: []
  };

  readSingleFile = function(f) {
    return parseFile(p, function(err, res) {
      addResult(res, result);
      result.summary = res.stats;
      return print(err, result, options, fmtOpts);
    });
  };

  readDir = function(dir) {
    var finish, processFile;
    finish = function(err, x) {
      result.summary = helpers.summarize(result.files.map(function(x) {
        return x.stats;
      }));
      return print(err, result, options, fmtOpts);
    };
    processFile = function(f, next) {
      return parseFile(f, function(err, r) {
        addResult(r, result);
        return next();
      });
    };
    return readdirp({
      root: dir,
      fileFilter: exts
    }, function(err, res) {
      return async.forEach(filterFiles(res.files), processFile, finish);
    });
  };

  p = programm.args[0];

  fs.lstat(p, function(err, stats) {
    if (err) {
      return console.error("Error: invalid path argument");
    }
    if (stats.isDirectory()) {
      return readDir(p);
    } else if (stats.isFile()) {
      return readSingleFile(p);
    }
  });

}).call(this);
