React = require 'react'
ReactDOM = require 'react-dom'
createClass = require 'create-react-class'
DialogueBox = React.createFactory(require './dialogue_box')
assign = require 'lodash/assign'
clone = require 'lodash/clone'

{div} = require 'react-dom-factories'

###
Dialogue Box Props

@props.message - String
  message to display

@props.confirmText - String - default: 'OK'
  text to display in okay/confirm button

@props.cancelText - String - default: 'Cancel'
  text gto display in the cancel button

@props.width - Number - default: 400
  width in pixels of the dialogue

@props.confirmCallback - method
  method to call when the 'ok' button is clicked or enter is pressed

@props.cancelCallBack - method
  method to call when the cancel button is clicked

@props.lightBackdrop - boolean
  show a lighter backdrop. e.g. when displayed over a modal
###
Dialogue = createClass
  
  displayName: 'Dialogue'

  getDefaultProps: ->
    {
      message: ''
      confirmText: 'OK'
      cancelText: 'Cancel'
      confirmCallback: ->
      cancelCallback: ->
      width: 400
      lightBackdrop: no
      height: 150
    }
  
  getInitialState: ->
    @top = -1 * @props.height
    {@top} 
  
  render: ->
    {top} = @state
    {lightBackdrop, height} = @props

    props = assign {}, @props, {
      @transitionOut
      top
      height
      ref: (@dialogue) =>
    }
    
    dialogue = DialogueBox(props)

    className = 'dialogue-container'
    className += ' light-backdrop' if lightBackdrop
      
    div {className}, dialogue

  componentDidMount: ->
    # Since this triggers a css transtion, need to wait until the next tick of the event loop
    setTimeout =>
      @setState {top: 0}
    , 0

  transitionOut: (btnValue) ->
    dialogueEl = ReactDOM.findDOMNode @dialogue
    
    dialogueEl.addEventListener 'transitionend', =>
      dialogueEl.removeEventListener 'transitionend', arguments.callee
      @handleTransitionEnd(btnValue)
    , no

    @setState {@top}
  
  handleTransitionEnd: (btnValue) -> 
    @props.cancelCallback()
    @props.confirmCallback() if btnValue is 'okay'
    


module.exports = Dialogue


