const { createLoaderMatcher } = require('./helpers');

const cssLoaderMatcher = createLoaderMatcher('css-loader');

// hardcoded search
const getCssRuleParent = (config, env) => config.module.rules[1];
const getCssRule = (config, env) => getCssRuleParent(config, env).oneOf[2];
const cssLoaderOptions = (oldOptions, env) => Object.assign({}, oldOptions, {
  modules: true,
  localIdentName: 'production' === env ? '__[hash:base64:8]' : '[name]__[local]___[hash:base64:5]',
});
const getList = rule => rule.use || rule.loader;

module.exports = function override(config, env) {

  const getCssModuleRuleParent = {
    test: /\.module\.css$/,
    use: getList(getCssRule(config, env)).map(rule => (
        rule.loader.indexOf('css-loader') !== -1 ? Object.assign({}, rule, { options: cssLoaderOptions(rule.options, env)}) : rule
      )
    ),
  };

  getCssRuleParent(config).oneOf.unshift(getCssModuleRuleParent);

  return config;
};

@@ -1,31 +1,191 @@
-const %7B createLoaderMatcher
+/*%0A* 1. Find existed CSS rule.%0A* 2. Create a CSSModules rule based on it (copy content by reference except for the css-loader!).%0A* 3. Insert it before CSS rule.%0A* */%0A%0Aconst %7B ruleChildren
  %7D =
@@ -217,22 +217,20 @@
 onst css
-Loader
+Rule
 Matcher 
@@ -235,221 +235,465 @@
 r = 
-createLoaderMatcher('css-loader');%0A%0A// hardcoded search
+rule =%3E rule.test && rule.test.toString() === /%5C.css$/.toString();%0A%0A// returns a triplet with parent rule, css rule, and index of css rule inside parent rule.
 %0Aconst 
-get
+find
 CssRule
+And
 Parent
- = (config, env) =%3E config.mod
+List = (rules) =%3E %7B%0A  return r
 ule
+s
 .r
-ules%5B1%5D;%0Aconst getCssRule = (config, env) =%3E get
+educe((acc, curr, ind) =%3E %7B%0A    if (acc.length) %7B%0A      return acc;%0A    %7D%0A    if (cssRuleMatcher(curr)) %7B%0A      return %5Brules, curr, ind%5D;%0A    %7D%0A    return find
 CssRule
+And
 Parent
-(config, env).oneOf%5B2%5D;%0Aconst cssLoader
+List(ruleChildren(curr));%0A  %7D, %5B%5D);%0A%7D;%0A%0Aconst withCssModules
 Opti
@@ -700,19 +700,16 @@
 ons = (o
-ldO
 ptions, 
@@ -739,11 +739,8 @@
 %7D, o
-ldO
 ptio
@@ -869,57 +869,8 @@
 %0A%7D);
-%0Aconst getList = rule =%3E rule.use %7C%7C rule.loader;
 %0A%0Amo
@@ -926,38 +926,109 @@
   const 
-getCssModule
+%5Bparent, css, index%5D = findCss
 Rule
+And
 Parent
+List(config.module.rules);%0A%0A  const cssModulesRule
  = %7B%0A   
@@ -1065,39 +1065,24 @@
 se: 
-getList(getCssRule(config, env)
+ruleChildren(css
 ).ma
@@ -1141,16 +1141,26 @@
 ) !== -1
+%0A         
  ? Objec
@@ -1193,17 +1193,22 @@
 ns: 
-cssLoader
+withCssModules
 Opti
@@ -1229,18 +1229,29 @@
 ns, env)
+ 
 %7D)
+%0A         
  : rule%0A
@@ -1263,17 +1263,16 @@
  )%0A    )
-,
 %0A  %7D;%0A%0A 
@@ -1276,59 +1276,41 @@
 %0A%0A  
-getCssRuleParent(config).oneOf.unshift(getC
+parent.splice(index, 0, c
 ssModule
 Rule
@@ -1309,18 +1309,13 @@
 dule
+s
 Rule
-Parent
 );%0A%0A

Refactor rewire-css-modules