import _ from 'lodash'
import postcss from 'postcss'
import cloneNodes from '../util/cloneNodes'
import buildMediaQuery from '../util/buildMediaQuery'
import buildSelectorVariant from '../util/buildSelectorVariant'

export default function(config) {
  return function(css) {
    const screens = config.screens
    const separator = config.options.separator
    const responsiveRules = postcss.root()
    let finalRules = []

    css.walkAtRules('responsive', atRule => {
      const nodes = atRule.nodes
      responsiveRules.append(...cloneNodes(nodes))
      atRule.before(nodes)
      atRule.remove()
    })

    _.keys(screens).forEach(screen => {
      const mediaQuery = postcss.atRule({
        name: 'media',
        params: buildMediaQuery(screens[screen]),
      })

      mediaQuery.append(_.tap(responsiveRules.clone(), clonedRoot => {
        clonedRoot.walkRules(rule => {
          rule.selectors = _.map(rule.selectors, selector =>
            buildSelectorVariant(selector, screen, separator, message => {
              throw rule.error(message)
            })
          )
        })
      }))

      finalRules.push(mediaQuery)
    })

    const hasScreenRules = finalRules.some(i => i.nodes.length !== 0)

    if (!hasScreenRules) {
      return
    }

    let includesScreensExplicitly = false

    css.walkAtRules('tailwind', atRule => {
      if (atRule.params === 'screens') {
        atRule.replaceWith(finalRules)
        includesScreensExplicitly = true
      }
    })

    if (!includesScreensExplicitly) {
      css.append(finalRules)
      return
    }
  }
}

@@ -794,16 +794,25 @@
 .append(
+%0A        
 _.tap(re
@@ -858,16 +858,18 @@
         
+  
 clonedRo
@@ -887,24 +887,26 @@
 s(rule =%3E %7B%0A
+  
           ru
@@ -966,16 +966,18 @@
         
+  
 buildSel
@@ -1027,24 +1027,26 @@
 essage =%3E %7B%0A
+  
             
@@ -1077,32 +1077,34 @@
 ge)%0A            
+  
 %7D)%0A          )%0A 
@@ -1100,16 +1100,31 @@
         
+  )%0A          %7D
 )%0A      
@@ -1128,24 +1128,22 @@
      %7D)%0A
+
       
-%7D)
 )%0A%0A     

Fix code style