context = window
ConfigureTracksStore = @ConfigureTracksStore
@ConfigureOutputsDialog = React.createClass({

  mixins: [Reflux.listenTo(@ConfigureTracksStore, "onConfigureTracksChanged"), Reflux.listenTo(@AppStore, "onAppInit")]

  onConfigureTracksChanged: (configureTracks) ->
    @setState({configureTracks: configureTracks})

  onAppInit: (@app) ->

  getInitialState: () ->
    {configureTracks: null}

  render: () ->

    outputs = []
    outputs.push(`<option key="" value="">Select an output port for session audio</option>`)

    if @state.configureTracks?
      for output in @state.configureTracks.musicPorts.outputs
        outputs.push(`<option key={output.id} value={output.id}>{output.name}</option>`)

    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/shared/icon_session.png" height={24} width={24}/>
        <h1>session audio outputs</h1>
      </div>
      <div className="dialog-inner">
        <p>Select two audio output ports that will be used to deliver the stereo audio of your sessions to your headphones or monitor.</p>
        <select className="output-1" >
          {outputs}
        </select>
        <select className="output-2" >
          {outputs}
        </select>
        <div className="actions">
          <a onClick={this.onCancel} className="button-grey">CANCEL</a>
          <a onClick={this.onClose} className="button-orange">UPDATE PORTS</a>
        </div>
      </div>
    </div>`

  componentDidUpdate: () ->
    $root = $(@getDOMNode())
    $output1 = $root.find('.output-1')
    $output2 = $root.find('.output-2')

    if @state.configureTracks? && @state.configureTracks.trackAssignments.outputs.assigned.length == 2

      output1 = @state.configureTracks.trackAssignments.outputs.assigned[0].id
      output2 = @state.configureTracks.trackAssignments.outputs.assigned[1].id

      $output1.val(output1)
      $output2.val(output2)

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

    $root = $(@getDOMNode())
    $output1 = $root.find('.output-1')
    $output2 = $root.find('.output-2')

    output1 = $output1.val()
    output2 = $output2.val()

    if output1 == null || output1 == ''
      context.JK.Banner.showAlert("Both output ports must have a selection.")
      return

    if output2 == null || output2 == ''
      context.JK.Banner.showAlert("Both output ports must have a selection.")
      return

    if output1? && output1 != '' && output1 == output2
      context.JK.Banner.showAlert("Both output ports can not be the same.")
      return

    ConfigureTracksActions.updateOutputs(output1, output2)

    @app.layout.closeDialog('configure-outputs-dialog', false)

  onCancel: (e) ->

    @app.layout.closeDialog('configure-outputs-dialog', true)
  }
)
