/* global module */
/* jslint node: true */
/* jslint indent: 2 */
'use strict';

/* Module Require */
var path = require('path'),
  async = require('async'),
  argv = require('minimist')(process.argv.slice(2)),
  express = require('express'),
  utils = require('tdm-utils');

var app = express();
var root = argv.root || './public',
  inputDir = argv.inputDir || '/data',
  httpPort = argv.httpPort || 3000;

app.use('/', express.static(path.resolve(__dirname, root)));

app.listen(httpPort, function() {
  console.log('listening on port : ' + httpPort);
  console.log('inputDir : ' + inputDir);
  console.log('root : ' + root);
  utils.corpusManager.prepare(inputDir, './public/data', function(err, res) {
    if (err) {
      console.log(err);
      return err;
    }
    console.log('prepare ok');
    async.each(res, function(item, callback) {
      var indexFile = path.join(item.out, 'indexAll.json');
      utils.corpusManager.indexAll(item.in, indexFile, function(err, res) {
        if (err) {
          console.log(err);
          return err;
        }
        console.log('indexation ok');
        var graphFile = path.join(item.out, 'graph.json');
        utils.graphs.docToDoc(res, {
          'output': graphFile,
          'minLinkValue': 5
        }, function(err, res) {
          if (err) {
            console.log(err);
            return err;
          }
          console.log('graph ok');
        });
      });
    }, function(err) {
      console.log(err);
      return err;
    });
  });
});