   document.head.appendChild(style)
   style
 
-removeStyleSheet = (style)->
-  style.parentNode?.removeChild(style)
+removeStyleSheet = (style)-> style.parentNode?.removeChild(style)
 
 getRules = (sheet)->
+  return unless sheet?
   sheet.cssRules || sheet.rules
 
 empty = (sheet)->

      r = r.replace(':host', prefix)
      if r.indexOf(prefix)>-1 then r else "#{prefix} #{r}"
    .join(', ')
    "#{selectorText} {#{rule.style.cssText}}"
  else
    subSheet = rule.cssRules || rule.rules
    if subSheet
      prefixRule(prefix, rule, subRule, j) for subRule, j in subSheet
    rule.cssText

appendStyle = (prefix, sheet, uri=window.location.href)->
  uri = getUriFromHref(sheet.href || uri)
  if !!sheet.href and !(sheet.cssRules || sheet.rules)
    # Loading External stylesheets (out of current domain)
    href = sheet.href
    sheet.ownerNode.parentNode.removeChild(sheet.ownerNode)
    fetch(href).then (text)->
      console.log "Loaded", href
      style = createStyleSheet(replaceLinkTagUrls(uri, text), true)
      appendRules sheet.cssRules, uri
      removeStyleSheet(style)
      true
  else
    rules = sheet.cssRules || sheet.rules
    appendRules(rules, uri)

replaceLinkTagUrls = (uri, text)->
  re = new RegExp "url\\(['\"]?([^)]*?)['\"]?\\)", "g"
  text.replace(re, "url('#{uri}$1')")

appendRules = (rules, uri)->
  _.map _.toArray(rules).reverse(), (rule)->
    cssText = rule.cssText
    BufferedStyles.sheet.insertRule(rule.cssText, 0)
  true

getUriFromHref = (href)->
  uri = href.split('/')

processDocument = (prefix, doc)->
  # Create and initialize a new global stylesheet that will receive merged styles in the right order
  MergedStyles = createStyleSheet("") unless MergedStyles
  # Under Firefox, you can't change css Rules or the containing
  # style tag or those will be reset when touching anything else.
  # Resort to building an entirely new stylesheet without copying cssRules

  # Promise manipulation ensures stylesheets are loaded in the correct order even if they are async.
  styles = doc.querySelectorAll('style,link')
  # IE doens't support inserting at any position.
  # Reverse stylesheets and insert from the end first.
  _.map styles, (style)->
    unless style.disabled
      style.disabled=true
      promise = promise.then ()->
        appendStyle(prefix, style)
      , (err)-> console.log err.message, err.stack

  promise.then ()->
    MergedStyles.textContent = "#{MergedStyles.textContent} #{Buffer}"
    Buffer=""
    true
  , (err)->
    console.log 'Something failed', err, err.stack

addStyle = (prefix, node)->
  # Array.prototype.slice.call(node.querySelectorAll('style:not([data-scoped])')).forEach (node)->
  node.setAttribute('data-scoped',true);
  new ScopedCss(prefix, null, node).process()

module.exports = {
  processDocument: processDocument
  addStyle: addStyle,
  addLink: addLink,
}
