Xmpp.Views.Chat ||= {}

class Xmpp.Views.Chat.WindowView extends Backbone.View
  template: JST["backbone/templates/chat/window"]
  el: $('#conversation-js')
  inputSelector: 'input[type=text]'

  maxHistoryLength: 20

  events:
    'submit #msg-writer': (e) -> @sendMessage(e)

  initialize: () ->
    _.bindAll(this)
    @tab = @attributes['tab']
    @historyStack = []

  render: ->
    historyStackHtml = _.map(@historyStack, (view) ->
      view.render().el.outerHTML
    )
    $(@el).html(@template(showWriter: true, history: historyStackHtml))
    @show()
    return this

  hide: ->
    $(@el).addClass('hidden')
    @undelegateEvents()
    this

  show: ->
    $(@el).removeClass('hidden')
    @delegateEvents()
    $(@el).find(@inputSelector).focus()
    this

  remove: ->
    @undelegateEvents()
    $(@el).empty()
    @stopListening()
    _.each(@historyStack, (item)->
      item.remove()
    )
    return this

  sendMessage: (e) ->
    e.preventDefault()
    $this = $(e.currentTarget)
    input = $this.find(@inputSelector)
    message = input.val()
    input.val('').focus()

    if (message.trim())
      chatId = @tab.getChatId()
      attendant = if not chatId then @tab.getAttendant().getPreferredResource() else null

      App.Models.me.sendMessage(message, chatId, attendant
      , (message) =>
        @sendSuccess(App.Models.me, message)
      , (message) =>
        @sendFail(message))

  sendSuccess: (me, msg) ->
    @appendMessage(me, new Date(), msg)

  sendFail: ->
    @appendEvent(I18n.t('chat.window.sendFailed'), false)

  appendEvent: (msg, logMe) ->
    App.debug ['append event', msg]
#    @log(eventView) if logMe == true

  appendMessage: (user, date, msg) ->
    messageView = new Xmpp.Views.Chat.MessageView(user: user, date: date, message: msg, fromMe: user.get('jid') == App.Models.me.get('jid'))
    $(@el).find('.messages').append(messageView.render().el)
    @log(messageView)
    Backbone.Events.trigger('resizeWorkspace')

  log: (view) ->
    if (@historyStack.length + 1 >= @maxHistoryLength)
      @historyStack = @historyStack.slice(@historyStack.length - @maxHistoryLength + 1)

    @historyStack.push(view)