/*
   * (non-Javadoc)
   *
   * @see net.jawr.web.resource.bundle.postprocess.
   * AbstractChainedResourceBundlePostProcessor
   * #doPostProcessBundle(net.jawr.web
   * .resource.bundle.postprocess.BundleProcessingStatus,
   * java.lang.StringBuffer)
   */
  @Override
  protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
      throws IOException {

    if (jsEngine == null) {
      initialize(status.getJawrConfig());
    }

    StopWatch stopWatch = new StopWatch();
    stopWatch.start("Processing Autoprefixer on '" + status.getLastPathAdded() + "'");

    String cssSource = bundleData.toString();
    String res = null;
    try {
      res = (String) jsEngine.invokeFunction("process", cssSource, options);

    } catch (NoSuchMethodException e) {
      throw new BundlingProcessException(e);
    } catch (ScriptException e) {
      throw new BundlingProcessException(e);
    }

    stopWatch.stop();
    if (PERF_LOGGER.isDebugEnabled()) {
      PERF_LOGGER.debug(stopWatch.shortSummary());
    }
    return new StringBuffer(res);
  }
  /** Initialize the postprocessor */
  private void initialize(JawrConfig config) {

    StopWatch stopWatch = new StopWatch("Initializing JS engine for Autoprefixer");
    stopWatch.start();

    // Load JavaScript Script Engine
    String script =
        config.getProperty(AUTOPREFIXER_SCRIPT_LOCATION, AUTOPREFIXER_SCRIPT_DEFAULT_LOCATION);
    String jsEngineName = config.getJavascriptEngineName(AUTOPREFIXER_JS_ENGINE);
    jsEngine = new JavascriptEngine(jsEngineName, true);
    jsEngine.getBindings().put("logger", PERF_LOGGER);
    InputStream inputStream = getResourceInputStream(config, script);
    jsEngine.evaluate("autoprefixer.js", inputStream);
    String strOptions =
        config.getProperty(AUTOPREFIXER_SCRIPT_OPTIONS, AUTOPREFIXER_DEFAULT_OPTIONS);
    this.options = jsEngine.execEval(strOptions);

    jsEngine.evaluate(
        "initAutoPrefixer.js", String.format("processor = autoprefixer(%s);", strOptions));
    jsEngine.evaluate(
        "jawrAutoPrefixerProcess.js",
        String.format(
            "function process(cssSource, opts){"
                + "var result = processor.process(cssSource, opts);"
                + "if(result.warnings){"
                + "result.warnings().forEach(function(message){"
                + "if(logger.isWarnEnabled()){"
                + "logger.warn(message.toString());"
                + "}"
                + "});}"
                + "return result.css;"
                + "}"));

    stopWatch.stop();
    if (PERF_LOGGER.isDebugEnabled()) {
      PERF_LOGGER.debug(stopWatch.shortSummary());
    }
  }