React = require 'react'
ReactDOM = require 'react-dom'

{iframe, object} = React.DOM

###
  @type - OPTIONAL - String
    file type to be set as an attribute on the iframe

  @src - REQUIRED - String
    the source of the document to be loaded in the iframe

  @className - OPTIONAL - String
    the CSS class set to the iframe

  @height - OPTIONAL - String | Number
    a fixed height for the container

  @width - OPTIONAL - String | Number 
    a fixed width for the container

  @ieObject - OPTIONAL - Boolean
    whether or not an <object> element will be used to accommodate IE

  @resizeContentAfterLoad - OPTIONAL - Function
    fired when the iframe finishes loading. This can be used to set a fixed height on a parent container in order to match the height of the embedded content. This is useful because iframes will not take the height of their content by default
###


IframeEmbedder = React.createClass

  displayName: 'IframeEmbedder'

  propTypes:
    type: React.PropTypes.string
    src: React.PropTypes.string.isRequired
    className: React.PropTypes.string
    height: React.PropTypes.oneOfType [
      React.PropTypes.string
      React.PropTypes.number
    ]
    width: React.PropTypes.oneOfType [
      React.PropTypes.string
      React.PropTypes.number
    ]
    ieObject: React.PropTypes.bool
    resizeContentAfterLoad: React.PropTypes.func

  getDefaultProps: ->
    height: '100%'
    width: '100%'
    className: 'iframe-embedded'
    type: ''

  render: ->
    {src, width, height, className, type, @ieObject} = @props

    if @ieObject
      object {
        className: className
        data: src
        type: type
        width: width
        height: '100%'
      }
    else
      iframe {
        className: className
        src: src
        width: width
        height: height
        ref: 'embeddedFrame'
      }


  componentDidMount: ->
    ReactDOM.findDOMNode(@refs.embeddedFrame).addEventListener('load', @resizeContentAfterLoad) unless @ieObject

  resizeContentAfterLoad: ->
    # What this does is it will size the iframe container to be the height of its content, removing the need for its own scrollbar
    # Added an extra 40px to accommodate IE scrollbar
    @props.resizeContentAfterLoad( ReactDOM.findDOMNode(@refs.embeddedFrame).contentDocument.getElementsByTagName('html')[0].scrollHeight + 40 )


module.exports = IframeEmbedder