class Xmpp.Models.Chat extends Xmpp.Models.Model
  namespace: 'app.chat'

  defaults:
    who: null
    withWhom: null
    chatId: null

  initialize: ->
    _.bindAll(this)

    App.Com.openNewChatId(@get('who').get('jid'), @get('withWhom').get('jid'), this)

  setChatId: (id) ->
    App.debug ['chat has id', id]
    @set('chatId', id)

class Xmpp.Collections.ChatsCollection extends Backbone.Collection
  model: Xmpp.Models.Chat

  initialize: ->
    _.bindAll(this)

    Backbone.Events.on('closeChat', (tab, chat) =>
      @removeChat(chat)
    )

  find: (who, withWhom) ->
    _.find(@models, (chat) ->
      chat.get('who') == who && chat.get('withWhom') == withWhom
    )

  removeChat: (chat) ->
    @models = _.without(@openedChats, chat)