/**
 * Created by nuintun on 2015/5/7.
 */

'use strict';

var css = require('css');

module.exports = function (code, opt){
  opt || (opt = {});

  if (Buffer.isBuffer(code)) {
    code = code.toString();
  }

  var ast = css.parse(code);

  if (opt.prefix) {
    var rules = ast.stylesheet.rules;
    
    ast.stylesheet.rules = parseRules(rules, opt.prefix);
  }

  return css.stringify(ast, { compress: true })
    .replace(/\\/g, '\\\\') // replace ie hack: https://github.com/spmjs/spm/issues/651
    .replace(/'/g, '"');
};

function parseRules(rules, prefix){
  return rules.map(function (o){
    if (o.selectors) {
      o.selectors = o.selectors.map(function (selector){
        // handle :root selector {}
        if (selector.indexOf(':root') === 0) {
          return ':root ' + prefix + ' ' + selector.replace(':root', '');
        }

        return prefix + ' ' + selector;
      });
    }

    if (o.rules) {
      o.rules = parseRules(o.rules, prefix);
    }

    return o;
  });
}
@@ -119,16 +119,20 @@
  opt
+ions
 )%7B%0A  opt
  %7C%7C 
@@ -131,16 +131,20 @@
  opt
+ions
  %7C%7C (opt
  = %7B
@@ -139,16 +139,20 @@
  %7C%7C (opt
+ions
  = %7B%7D);%0A
@@ -255,16 +255,20 @@
  if (opt
+ions
 .prefix)
@@ -308,20 +308,16 @@
 .rules;%0A
-    
 %0A    ast
@@ -357,16 +357,20 @@
 les, opt
+ions
 .prefix)

add source files