var _ = require('underscore');
var sass = require('node-sass');
var through = require('through2');
var path = require('path');

var sassDefaults = {
  outputStyle: 'compressed'
};

module.exports = sassr;

function sassr(file, opts) {

  if (!/\.(scss|css)$/.test(file)) return through();

  opts = _.defaults({}, opts, sassDefaults);

  var buffer = '';

  function push(chunk, enc, cb) {
    buffer += chunk;
    cb();
  }

  function end(cb) {
    var stream = this;
    sass.render({
      data: buffer,
      success: success,
      error: error,
      includePaths: [path.dirname(file)].concat(opts.includePaths),
      outputStyle: opts.outputStyle
    });
    function success(css) {
      var moduleBody = sassrModuleWith( JSON.stringify(css) );
      stream.push( moduleBody );
      cb();
    }
    function error(err) {
      var message = 'sassr: ' + err + ' in ' + file;
      var moduleBody = errorModuleWith(message);
      stream.push( moduleBody );
      stream.emit('error', message);
      cb();
    }
  }

  return through(push, end);
}

function sassrModuleWith(css) {
  return [
    'var style = require("sassr/style");',
    'var css = ' + css + ';',
    'var appended;',
    'module.exports.append = function() {',
    '  if (!appended) style.inject(css);',
    '  appended = true;',
    '  return style.style;',
    '};',
    'module.exports.remove = function() {',
    '  if (appended) style.eject(css);',
    '  appended = false;',
    '  return style.style;',
    '};'
  ].join('\n');
}

function errorModuleWith(message) {
  return [
    'var style = require("sassr/style");',
    'module.exports.append = module.exports.remove = function() {',
    '  console.error("' + message + '");',
    '  return style;',
    '};'
  ].join('\n');
}

@@ -142,16 +142,36 @@
 lts = %7B%0A
+  includePaths: %5B%5D,%0A
   output
@@ -190,16 +190,16 @@
 ressed'%0A
-
 %7D;%0A%0Amodu
@@ -303,16 +303,73 @@
 ugh();%0A%0A
+  var omitFields = %5B'file', 'data', 'success', 'error'%5D;%0A
   opts =
@@ -369,16 +369,23 @@
  opts = 
+_.omit(
 _.defaul
@@ -410,16 +410,29 @@
 efaults)
+, omitFields)
 ;%0A%0A  var
@@ -576,16 +576,27 @@
 .render(
+_.defaults(
 %7B%0A      
@@ -723,51 +723,21 @@
 ths)
-,
 %0A    
-  outputStyle: opts.outputStyle%0A    %7D
+%7D, opts)
 );%0A 
@@ -1242,24 +1242,24 @@
  css + ';',%0A
-
     'var app
@@ -1263,24 +1263,179 @@
 appended;',%0A
+    'module.exports.el = function() %7B',%0A    '  return style.style;',%0A    '%7D;',%0A    'module.exports.cssText = function() %7B',%0A    '  return css;',%0A    '%7D;',%0A
     'module.

allow more node-sass options, add el() and css()