#!/usr/bin/env node

var juice = require('..');
var cli = require('../lib/cli');
var fs = require('fs');
var path = require('path');

var program = cli.getProgram();

if (program.args.length < 2) {
  program.help();
}

var [inputFile, outputFile] = program.args;
var options = cli.argsToOptions(program);
var queue = [];

if (options.optionsFile) {
  var optionsFromFile = require(path.resolve(process.cwd(),options.optionsFile));
  options = Object.assign({}, optionsFromFile, options, {
    webResources: Object.assign(
      {},
      optionsFromFile && optionsFromFile.webResources,
      options && options.webResources
    )
  });
}

if (options.cssFile) {
  queue.push(function() {
    fs.readFile(options.cssFile, function(err, css) {
      if (handleError(err)) { return; }
      options.extraCss = css.toString();
      next();
    });
  });
}

next();

function doJuice() {
  delete options.cssFile;
  delete options.optionsFile;

  juice.juiceFile(inputFile, options, function(err, html) {
    if (handleError(err)) { return; }
    fs.writeFile(outputFile, html, handleError);
  });
}

function next() {
  if (queue.length) {
    return queue.pop()();
  }
  doJuice();
}

function handleError(err) {
  if (err) {
    console.error(err.stack);
    process.exit(1);
  }
  return !!err;
}
