const isObject = require('isobject')

const { withUnits } = require('./units')

const format = customMedia => customMedia.map(breakpoint => {
  const key = Object.keys(breakpoint)[0]
  const value = breakpoint[key]

  if (isObject(value)) {
    return Object.assign({}, breakpoint[key], {
      key,
      value: value.value
    })
  } else {
    return { key, value }
  }
})

module.exports = config => {
  const formatted = format(config.customMedia)

  const minMaxMedia = formatted.filter(s => !isMinWidthQuery(s))
  const minMaxQueries = minMaxMedia.map((breakpoint, i) => {
      const nextBreakpoint = minMaxMedia[i+1]

      const mq = [
        'screen',
        `(min-width: ${withUnits(breakpoint.value)})`
      ]

      if (nextBreakpoint) {
        mq.push(`(max-width: ${withUnits(nextBreakpoint.value)})`)
      }

      return Object.assign({}, breakpoint, { mq: mq.join(' and ') })
    })

  const minQueries = formatted
    .filter(isMinWidthQuery)
    .map(breakpoint => {
      const mq = `screen and (min-width: ${withUnits(breakpoint.value)})`

      return Object.assign({}, breakpoint, { mq })
    })

  return minMaxQueries.concat(minQueries)
}

const isMinWidthQuery = breakpoint => breakpoint.minWidth

module.exports.format = format

@@ -573,26 +573,24 @@
 i) =%3E %7B%0A    
-  
 const nextBr
@@ -618,26 +618,24 @@
 a%5Bi+1%5D%0A%0A    
-  
 const mq = %5B
@@ -641,18 +641,16 @@
 %5B%0A      
- 
- 
 'screen'
@@ -651,18 +651,16 @@
 creen',%0A
-  
       %60(
@@ -703,18 +703,16 @@
 lue)%7D)%60%0A
-  
     %5D%0A%0A 
@@ -714,18 +714,16 @@
  %5D%0A%0A    
-  
 if (next
@@ -736,18 +736,16 @@
 oint) %7B%0A
-  
       mq
@@ -809,15 +809,11 @@
     
- 
- 
 %7D%0A%0A
-  
     
@@ -871,26 +871,24 @@
 ' and ') %7D)%0A
-  
   %7D)%0A%0A  cons

Fix formatting