/**
 * css-selector-extract
 * @author Markus Oberlehner
 */
'use strict';

import postcss from 'postcss';
import postcssScss from 'postcss-scss';

export default class CssSelectorExtract {
  process(css, selectors, replacementSelectors) {
    return new Promise((resolve, reject) => {
      let css = this.processSync(css, selectors, replacementSelectors);
      resolve(css);
    });
  }

  processSync(css, selectors, replacementSelectors) {
    return postcss(postcss.plugin('postcss-extract-selectors', (options) => {
      return (cssNodes) => {
        cssNodes.walkRules((rule) => {
          // Split combined selectors into an array.
          let ruleSelectors = rule.selector.split(',').map((ruleSelector) => ruleSelector.replace(/(\r\n|\n|\r)/gm, '').trim());
          // Find whitelisted selectors and remove others.
          ruleSelectors.forEach((ruleSelector, index) => {
            let selectorFilterIndex = selectors.indexOf(ruleSelector);
            if (selectorFilterIndex != -1) {
              ruleSelectors[index] = replacementSelectors[ruleSelector];
            } else {
              // Set an empty value for the selector to mark it for deletion.
              ruleSelectors[index] = '';
            }
          });
          // Remove empty selectors.
          ruleSelectors = ruleSelectors.filter((ruleSelector) => ruleSelector.length > 0 || false);
          if (ruleSelectors.length) {
            rule.selector = ruleSelectors.join(',');
          } else {
            // Remove the rule.
            rule.remove();
          }
        });
      };
    })).process(css, { syntax: postcssScss }).css;
  }
}

@@ -289,19 +289,22 @@
     let 
-css
+result
  = this.
@@ -368,19 +368,22 @@
 resolve(
-css
+result
 );%0A    %7D
@@ -463,16 +463,199 @@
 postcss(
+this._postcssSelectorExtract(selectors, replacementSelectors)).process(css, %7B syntax: postcssScss %7D).css;%0A  %7D%0A%0A  _postcssSelectorExtract(selectors, replacementSelectors) %7B%0A    return 
 postcss.
@@ -1160,43 +1160,70 @@
     
-if (selectorFilterIndex != -1) %7B%0A  
+// Replace the selector if a replacement selector is defined.%0A
     
@@ -1291,28 +1291,76 @@
 tor%5D
-;%0A            %7D else
+ %7C%7C ruleSelectors%5Bindex%5D;%0A            if (selectorFilterIndex == -1)
  %7B%0A 
@@ -1854,51 +1854,8 @@
   %7D)
-).process(css, %7B syntax: postcssScss %7D).css
 ;%0A  

use a separate function for the postcss extract plugin, fix problems with selector replacements which occured because of the old extraction selector variable format (fixes #1)