#!/usr/bin/env node
/* file : cli.js
MIT License

Copyright (c) 2016 Thomas Minier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

'use strict';

/**
 * Simple Command Line Interface for a Carson application
 * @author Thomas Minier
 */

const path = require('path');
const program = require('commander');
const Carson = require('./src/carson.js');
const infos = require('./package.json');

/**
 * Transform a path to an absolute one
 * @param {string} oldPath - A path to a file
 * @return {string} The absolute version of the path given in parameter
 */
const toAbsolutePath = oldPath => {
	if (path.isAbsolute(oldPath)) {
		return oldPath;
	}
	return path.resolve(oldPath);
};

program.version(infos.version)
	.description(infos.description)
	.usage('<config-file> <output> [options]')
	.option('-p, --progress', 'display progress during execution');
program._name = infos.name;

program.parse(process.argv);

if (program.args.length < 2) {
	process.stderr.write('Error: carson should be called with the following args : carson <config-file> <output> [options]\nUse carson -h to display usage informations.\n');
	process.exit(1);
}

// ensure that both config path & results paths are absolute before using them
const config = require(toAbsolutePath(program.args[0]));
const resultOutput = toAbsolutePath(program.args[1]);

// enable logging if needed
let logger;
if (program.progress) {
	logger = log => process.stdout.write(`[${log.level.toUpperCase()}] ${log.date} ${log.message}\n`);
}

// create and run the application
const app = new Carson(resultOutput, logger);
app.loadConfig(config)
	.then(() => app.run())
	.then(() => process.stdout.write('Execution completed !\n'))
	.catch(error => process.stderr.write(error + '\n'));
