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)

  syncContacts: (contacts, owner) ->
    contactsWithoutMe = _.filter(contacts, (jid) ->
      jid != App.Models.me.get('jid')
    )

    if (owner != App.Models.me.get('jid'))
      contactsWithoutMe = contactsWithoutMe.concat([owner]);

    attendants = _.map(contactsWithoutMe, (jid) =>
      contact = App.Collections.contacts.findByJid(jid)
      if not contact
        newTempContact = @createTempContact(jid)
        App.Collections.contacts.add(newTempContact)
        contact = newTempContact

      contact
    )

    @set('withWhom', attendants);

    if owner
      ownerContact = App.Collections.contacts.findByJid(owner)
      if not ownerContact
        ownerContact = @createTempContact(owner)
        App.Collections.contacts.add(ownerContact)

      @set('who', ownerContact)

    App.debug ['importing contacts to chat', this]


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)

  createTempContact: (jid) ->
    newTempContact = new Xmpp.Models.Contact(jid: jid, belongsTo: [App.Models.me])
    newTempContact