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

  defaults:
    who: null
    withWhom: null
    chatId: null
    isMultiChat: false

  initialize: ->
    _.bindAll(this)

    if (@get('isMultiChat'))
      @set('withWhom', [])

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

  appendWithWhom: (newPerson) ->
    allWithWhom = @get('withWhom');

    exists = _.find(allWithWhom, (withWhom) ->
      withWhom == newPerson
    )?

    if not exists
      allWithWhom.push(newPerson)

  setChatId: (id) ->
    App.debug ['multichat 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
    )

  findById: (id) ->
    @findWhere(chatId: id)

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