context = window
JamBlasterActions = @JamBlasterActions

@JamBlasterPairingDialog = React.createClass({

  mixins: [@BonjourMixin, Reflux.listenTo(@AppStore, "onAppInit"),   Reflux.listenTo(@JamBlasterStore, "onJamBlasterChanged")]


  beforeShow: (args) ->
    logger.debug("JamBlasterPairingDialog.beforeShow", args.d1)
    @setState({timer: null, pairing: false, bonjourClientId: args.d1, pairingTimeout: false, paired: false})
    JamBlasterActions.resyncBonjour()
    @setTimer(false)

  afterHide: () ->
    @clearTimer()

  onAppInit: (@app) ->
    dialogBindings = {
      'beforeShow': @beforeShow,
      'afterHide': @afterHide
    };

    @app.bindDialog('jamblaster-pairing-dialog', dialogBindings);

  onJamBlasterChanged: (jamblasterState) ->
    @setState(jamblasterState)

  getInitialState: () ->
    {
      timer: null,
      pairing: false,
      pairStart: null,
      allJamBlasters: [],
      pairingTimeout: false,
      paired: false,
      userJamBlasters: [],
      localJamBlasters: []
    }

  clearTimer: () ->
    if @interval?
      clearInterval(@interval)
      @interval = null

  clearPairingTimer: () ->
    if @pairingInterval?
      clearInterval(@pairingInterval)
      @pairingInterval = null

  setTimer: (connecting) ->
    @clearTimer()

    if connecting
      time = 5000 # every 5 seconds
    else
      time = 60000 # every minute

    @interval = setInterval((() => JamBlasterActions.resyncBonjour()), time)

  pairingTimer: () ->
    @clearPairingTimer()

    @pairingInterval = setInterval((() => @updatePairingTimer()), 800)

  updatePairingTimer: () ->

    now = new Date().getTime()

    delta = (now - @state.pairStart) / 1000

    if delta > 60
      @clearPairingTimer()
      @setTimer(false)
      @setState({pairing: false, pairingTimeout: true, timer: null})
    else
      client = @findJamBlaster(@state.bonjourClientId)
      if client.isPaired
        @clearPairingTimer()
        @setTimer(false)
        @setState({pairing: false, pairingTimeout: false, timer: null, paired: true})
      else
        @setState({timer: 60 - delta})

  componentDidMount: () ->
    @root = $(@getDOMNode())
    @dialog = @root.closest('.dialog')

  componentDidUpdate: () ->

  doCancel: (e) ->
    e.preventDefault()

    if @state.pairing
      return

    @app.layout.closeDialog('jamblaster-pairing-dialog', true);

  close: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('jamblaster-pairing-dialog')

  pair: (e) ->
    e.preventDefault()

    if @state.pairing
      return

    @setState({pairing: true, pairStart: new Date().getTime(), timer: 60, pairingTimeout: false, paired: false})
    @setTimer(true)

    client = @findJamBlaster(this.state.bonjourClientId)

    if client.isPaired
      context.JK.Banner.showNotice("JamBlaster already paired", "This JamBlaster is already paired.")
      @app.layout.closeDialog("jamblaster-pairing-dialog", true)
    else if client?
      logger.debug("trying to connect to #{client.connect_url}")
      if client.connect_url?
        @pairingTimer()
        context.jamClient.startPairing(client.connect_url)
      else
        context.JK.Banner.showAlert("JamBlaster offline", "JamBlaster appears to be offline.  Please reboot it.")
    else
      context.JK.Banner.showAlert("JamBlaster offline", "JamBlaster appears to be offline.  Please reboot it.")

  render: () ->

    if @state.pairing
      countdown =  `<div className="countdown-msg">You have <span className="countdown">{Math.round(this.state.timer)}</span> seconds to push the button on the back of the JamBlaster.
        </div>`
    else
      countdown = null


    cancelClasses = {"button-grey": true, disabled: @state.pairing}
    connectClasses = {"button-orange": true, disabled: @state.pairing}

    actions = `<div className="actions">
      <a onClick={this.doCancel} className={classNames(cancelClasses)}>CANCEL</a>
      <a onClick={this.pair} className={classNames(connectClasses)}>CONNECT</a>
    </div>`


    if @state.paired
      message = `<p className="message">You have successfully connected to this JamBlaster!</p>`
      actions = `<div className="actions">
        <a onClick={this.close} className="button-orange">CLOSE</a>
      </div>`
    else if @state.pairingTimeout
      message = `<p className="message">No connection established. You may click the CONNECT button to try again. If you cannot connect, please contact us at support@jamkazam.com.</p>`
    else

    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/content/icon_add.png" height={19} width={19}/>

        <h1>connect to JamBlaster</h1>
      </div>
      <div className="dialog-inner">

        <p>To connect this application/device with the selected JamBlaster, please click the CONNECT button below, and then push the small black plastic button located on the back of the JamBlaster between the USB and power ports to confirm this pairing within 60 seconds of clicking the Connect button below.</p>

        {message}

        {countdown} {actions}
      </div>
    </div>`

})