 ScopedCssRule  = require 'scopedcss/lib/cssRule';
 superagent          = require 'superagent'
 
-Styles     = {}
-MergedStyles  = null;
+Styles     = []
 
-# replaceRule = (sheet, selector, cssText, index)->
-#     if sheet.removeRule then sheet.removeRule(index) else sheet.deleteRule(index);
-#     rule = if selector then selector + '{' + cssText + '}' else cssText
-#     if sheet.addRule then sheet.addRule(selector, cssText, index) else sheet.insertRule(rule, index);
 
 createStyleSheet = (content="", disabled=false)->
   style = document.createElement('style')

    content = (prefixRule(prefix, subRule) for subRule, j in subSheet)
    query = rule.cssText.split('{');
    return "#{query[0]} {#{content.join(' ')}} "

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

addLink = (prefix, node)->
  appendStyle(prefix, node, getUriFromHref(node.href))

promise = new Promise (resolve, reject)-> resolve()

###*
 * Processes a complete document and writes a merged, prefixed stylesheet into the Main Document's HEAD.
 * @param  {string} prefix prefix to add to every style
 * @param  {[type]} doc    document to collapse into a single Stylesheet
###
processDocument = (prefix, doc)->
  # Promise manipulation ensures stylesheets are loaded in the correct order even if they are async.
  styles = _.toArray(doc.querySelectorAll('style,link'))
  # IE doesn'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)
      , throwErr

  promise.then ()->
    MergedStyles.textContent = _.pluck(Styles,'style').join(' ');
  , throwErr


addDocument = (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
  Styles[prefix] = {doc: doc, style:""}
  processDocument(prefix, hash.doc) for prefix, hash of Styles

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 = {
  addDocument : addDocument
  addStyle    : addStyle
  addLink     : addLink
}


removeStyleSheet = (style)-> style.parentNode?.removeChild(style)

# Create and initialize a new global stylesheet that will receive merged styles in the right order
MergedStyles = createStyleSheet("") unless MergedStyles

# A single promise will guarantee execution order;
promise = new Promise (resolve, reject)-> resolve()

getRules = (sheet)->
  return unless sheet?
  sheet.cssRules || sheet.rules
appendRules = (entry, rules)->
  r = _.map rules, (rule)->
    prefixRule(entry.prefix, rule);
  entry.style = r.join(' ');
  true
empty = (sheet)->
  if sheet.deleteRule?
    sheet.deleteRule(0) while getRules(sheet).length > 0
  else if sheet.removeRule?
    sheet.removeRule(0) while getRules(sheet).length > 0
fetch = (href)->
  new Promise (resolve, reject)->
    superagent.get(href).end (err, res)-> resolve(res.text)
replaceLinkTagUrls = (uri, text)->
  re = new RegExp "url\\(['\"]?([^)]*?)['\"]?\\)", "g"
  text.replace(re, "url('#{uri}$1')")
prefixRule = (prefix, rule)->
  return unless rule
  if rule.selectorText
