#!/usr/bin/env node
var colors    = require('colors');
var fs        = require('fs');
var sass      = require('../sass');
var path      = require('path');
var argv      = require('optimist').argv;

var fileName  = argv._[0];
var cssFileName = argv._[1];
var outputStyle = argv['output-style'];
var cwd = argv.cwd || process.cwd();

console.log('Starting Render Process...'.green);

if (fileName) {
  fs.readFile(path.join(cwd, fileName), "utf8", function(err, data) {
    if (err) {
      console.log("** Error Opening File **".red);
      console.log(JSON.stringify(err, null, 4).yellow);
    } else {
      console.log('File data read successfully, rendering css'.green);
      renderSASS(data);
    }
  });
} else {
  console.log("** Please Pass a filename to compile **".red);
}

function renderSASS(data) {
  sass.render(data, function(err, compiled) {
    if (err) {
      console.log("** Error Rendering SASS **".red);
      console.log(JSON.stringify(err, null, 4).yellow);
    } else {
      console.log('Rendering Complete, saving .css file...'.green);

      var outFile;
      if (cssFileName) {
        outFile = cssFileName;
      } else {
        outFile = fileName.slice(fileName.lastIndexOf('/') + 1,
                  fileName.lastIndexOf('.')) + '.css';
      }

      writeCssFile(outFile || 'nodesass.css', compiled);

    }
  }, {include_paths: [cwd], output_style: outputStyle});
}

function writeCssFile(filename, data) {
  fs.writeFile(path.join(cwd, filename), data, function(err){
    if(err) {
      console.log('Error: ' + err);
    } else {
      console.log('File saved! New .css file: ' + filename);
    }
  });
}
