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
  savingHistory: true
  historyStep: 0

  events:
    'submit #msg-writer': (e) -> @sendMessage(e)
    'change .history-settings input': 'changeHistorySettings'
    'click .history-settings .load-history': 'loadHistory'

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

    chatId = @tab.getChatId()
    attendant = if not chatId then @tab.getAttendant().get('jid') else null

    App.Com.checkSavingHistory(App.Models.me.get('jid'), chatId, attendant, (canSave) =>
      @savingHistory = canSave
      @_changeHistoryVisibly(@savingHistory)
    )

    @loadHistory()

  render: ->
    historyStackHtml = _.map(@historyStack, (view) ->
      view.render().el.outerHTML
    )
    $(@el).html(@template(hideHistoryLoading: @tab.getChatId() != null, history: historyStackHtml))
    @_changeHistoryVisibly(@savingHistory)

    @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, idMessage) ->
    if idMessage
      return if @_checkIfMessageExists(idMessage)

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

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

    if not isHistoryMessage? || isHistoryMessage == false
      @historyStack.push(view)
    else
      @historyStack.unshift(view)

  changeHistorySettings: (e) ->
    $input = $(e.currentTarget)
    state = $input.is(':checked')

    chatId = @tab.getChatId()
    attendant = if not chatId then @tab.getAttendant().getPreferredResource() else null
    App.Com.setHistory(App.Models.me.get('jid'), chatId, attendant, state, =>
      @savingHistory = state
      @_changeHistoryVisibly(state)
    )

  _changeHistoryVisibly: (currentState) ->
    if currentState
      toEnable = '.enabled'
      toDisable = '.disabled'
    else
      toEnable = '.disabled'
      toDisable = '.enabled'

    $(@el).find(".action#{toEnable}, .current#{toEnable}").show()
    $(@el).find(".action#{toDisable}, .current#{toDisable}").hide()

  prependHistoryMessage: (user, date, msg, msgId) ->
    if msgId
      return if @_checkIfMessageExists(msgId)

    messageView = new Xmpp.Views.Chat.MessageView(user: user, date: date, message: msg, fromMe: user.get('jid') == App.Models.me.get('jid'), idMessage: msgId)
    $(@el).find('.messages').prepend(messageView.render().el)
    @log(messageView, true)

  loadHistory: ->
    chatId = @tab.getChatId()
    attendant = if not chatId then @tab.getAttendant().get('jid') else null

    App.Com.loadHistory(App.Models.me.get('jid'), chatId, attendant, @historyStep, (result) =>
      App.debug result

      _.each(result.history.reverse(), (message) =>
        jid = App.stripJid(message.from)
        if App.Models.me.get('jid') == jid
          contact = App.Models.me
        else
          contact = App.Collections.contacts.findByJid(jid) || Xmpp.Collections.ChatsCollection.createTempContact(jid)

        @prependHistoryMessage(contact, new Date(message.created_at), message.message, message.id)
      )

      @historyStep++ unless _.isEmpty(result.history)
    )

  _checkIfMessageExists: (idMessage) ->
    _.find(@historyStack, (message) ->
      message.idMessage == idMessage
    )