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', [])

  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)

  isMeOwner: ->
    @get('who') == App.Models.me

  isAttending: (contact) ->
    attendants = @get('withWhom')
    if _.isArray(attendants)
      return _.find(attendants, (somebody) -> somebody == contact)
    else
      return contact == attendants

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

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

    attendants = _.map(contactsWithoutMe, (jid) =>
      contact = App.Collections.contacts.findByJid(jid)
      if not contact
        contact = new Xmpp.Models.Contact(
          id: App.stripJid(jid)
          jid: App.stripJid(jid)
          belongsTo: [App.Models.me.get('jid')]
          usingMyApp: true
        )
        App.Collections.contacts.add(contact)

      contact
    )

    @set('withWhom', attendants);

    if owner
      ownerContact = App.Collections.contacts.findByJid(owner)
      @set('who', ownerContact)

    App.debug ['importing contacts to chat', this, this.get('chatId')]


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

  initialize: ->
    _.bindAll(this)

    Backbone.Events.on('closeChat', (chat, ignoreCheckIfMultichat) =>
      @removeChat(chat)
      if not ignoreCheckIfMultichat
        if (chat.get('isMultiChat'))
          App.Com.iClosedMultichat(chat.get('chatId'), App.Models.me.get('jid'))
    )

    Backbone.Events.on('openChat', (chat) =>
      @activeChat = chat
    )

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

  findById: (id) ->
    _.find(@models, (chat) ->
      chat.get('chatId') == id
    )

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

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