var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;

module.exports = function(opt){
  function modifyFile(file){
    if (file.isNull()) return this.emit('data', file); // pass along
    if (file.isStream()) return this.emit('error', new Error("gulp-coffee: Streaming not supported"));

    var str = file.contents.toString('utf8');

    var options = {};

    if ( opt ) {
      options = {
        bare: opt.bare != null ? !!opt.bare : false,
        literate: opt.literate != null ? !!opt.literate : false,
        sourceMap: opt.sourceMap != null ? !!opt.sourceMap : false
      }
    }

    try {
      file.contents = new Buffer(coffee.compile(str, options));
    } catch (err) {
      var newError = formatError(file, err);
      return this.emit('error', newError);
    }
    file.path = gutil.replaceExtension(file.path, ".js");
    this.emit('data', file);
  }

  return es.through(modifyFile);
};
