#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var program = require('commander');
var debug = require('debug')('Validator');

var pkg = require('./package.json');
var errorHandler = require('./lib/errorhandler')();
var htmlValidator = require('./lib/html-validator')(errorHandler);
var cssValidator = require('./lib/css-validator.js')(errorHandler);

var resourceSpec = require('./data/resource_spec.json');
var localeSpec = require('./data/locale.json');

function validate(filePath, options) {
  var result = htmlValidator.validate(filePath, options);

  result['css'].map(function(e){
    cssValidator.validate(e.text, e.basePath, e.filePath, e.loc.line - 1, options);
  });
}

program
  .version(pkg.version)
  .usage('<.html file> [options]')
  .option('-p, --profile [value]', 'profile [optional] [default: wearable]')
  .option('-l, --language [value]', 'language [optional]')
  .parse(process.argv);

var filePath = program.args[0];
var fileName = path.basename(filePath);
var options = {
  'profile': 'wearable',
  'lang': null
};

//parsing arguments.
try {
  if (program.args.length !== 1)
    throw new Error('no target file')

  var stat = fs.statSync(filePath);
  if (!stat.isFile())
    throw new Error('No such file');

  if (path.extname(fileName) != '.html')
    throw new Error(fileName + ' is not html file');

  if (program.profile) {
    if (resourceSpec[program.profile] === undefined)
      throw new Error(program.profile + ' is invalid profile');
    options.profile = program.profile;
  } else {
    // TODO : Need to read the config.xml for checking the profile
  }

} catch(e) {
  debug(e);
  console.error('Error : ' + e.message);

  program.help();
  process.exit(1);
}

//validate.
if (program.language) {
  if (localeSpec.support.indexOf(file) !== -1)
    options.lang = program.language;
} else {
  var localePath = path.join(path.dirname(filePath), 'locales');
  try {
    var files = fs.readdirSync(localePath);
    files.map(function(file) {
      var localeStat = fs.statSync(path.join(localePath, file));
      if (localeStat.isDirectory()) {
        if (localeSpec.support.indexOf(file) !== -1) {
          debug("Test locale: " + file);

          options.lang = file;
          validate(filePath, options);
        } else
          debug("Not Support the locale: " + file);
      }
    });
  } catch (err) {
    debug(err);
  }
  options.lang = null;
}

validate(filePath, options);
errorHandler.printErrors({hint: true});