import React from 'react'
import { css, StyleSheetManager } from 'styled-components'
import hashStr from 'styled-components/lib/vendor/glamor/hash'
import stringifyRules from 'styled-components/lib/utils/stringifyRules'

const CONTEXT_KEY = '__styled-components-stylesheet__'

export default (...args) =>
  // Returns a React Component
  class InjectGlobal extends React.Component {
    constructor (props, context) {
      super(props)
      console.log(JSON.stringify(StyleSheetManager))
      // Uses the context to gain access to the stylesheet if possible
      const styleSheet = context[CONTEXT_KEY] || StyleSheet
      // The normal stuff...
      const rules = css(...args)
      const hash = hashStr(JSON.stringify(rules))
      const id = `sc-global-${hash}`

      if (!styleSheet.hasId(id)) {
        styleSheet.inject(id, stringifyRules(rules))
      }
      // Probably want some logic to make sure this only runs once...
    }
    render () {
      // Render the child
      return this.props.children ? React.Children.only(this.props.children) : null
    }
  }
