context = window

@ChatDialog = React.createClass({

  mixins: [@PostProcessorMixin, Reflux.listenTo(@AppStore, "onAppInit"), Reflux.listenTo(@SessionStore, 'onSessionChanged')]
  teacher: false

  beforeShow: (args) ->
    logger.debug("ChatDialog.beforeShow", args.d1)

    parsed = @parseId(args.d1)

    if parsed.type == 'session'
      window.ChatActions.activateChannel('session')
      @setState({id: parsed.id, type: parsed.type, lesson_session: null})

    else if args.d1 == 'global'
      window.ChatActions.activateChannel('global')
      @setState({id: null, type: 'global', lesson_session: null})

    else if parsed.type == 'lesson'
      window.ChatActions.initializeLesson.trigger(parsed.id)

      @setState({id: parsed.id, type: parsed.type, lesson_session: null})

      if parsed.type == "lesson"
        rest.getLesson({id: parsed.id}).done((response) => @getLessonDone(response)).fail((jqXHR) => @getLessonFail(jqXHR))
    else
      context.JK.Banner.showAlert('unknown chat type', "chat type was #{parsed.type}")


  getLessonDone: (lesson_session) ->
    @postProcessLesson(lesson_session)
    @setState({lesson_session: lesson_session})

  getLessonFail: (jqXHR) ->
    @app.ajaxError(jqXHR)

  afterHide: () ->
    if !@session
      window.ChatActions.activateChannel('global')


  parseId:(id) ->
    if !id?
      {id: null, type: null}
    else
      bits = id.split('_')
      if bits.length == 2
        {id: bits[1], type: bits[0]}
      else
        {id: null, type: null}

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

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

  onSessionChanged: (session) ->
    @session = session

  componentDidMount: () ->
    @root = $(@getDOMNode())

  getInitialState: () ->
    {id: null, type: null, lesson_session: null}

  onCloseClicked: (e) ->
    @app.layout.closeDialog('chat-dialog');


  render: () ->

    if this.state.lesson_session?
      title = "#{this.state.lesson_session.music_session.scheduled_start_date} lesson chat"
      lessonSessionId = this.state.lesson_session.id
      other = this.state.lesson_session.other
    else
      title = 'Session Chat'
      other = null
      lessonSessionId = null

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

        <h1>{title}</h1>
      </div>
      <div className="dialog-inner">
        <ChatWindow newFormat={true} channel={lessonSessionId} hideHeader={true} rootClass="ChatDialog" showEmailNotice={true} showClose={true} other={other} onCloseClicked={this.onCloseClicked} channelType="lesson" />
      </div>
    </div>`

})