class Xmpp.Models.Contact extends Xmpp.Models.Model
  namespace: 'app.roster'

  defaults:
    jid: ''
    name: ''
    status: 'offline'
    message: ''
    avatar: ''
    belongsTo: ''

  initialize: ->
    _.bindAll(this)

    if ! @get('name')
      @set(name: @get('jid'))

  firstname: ->
    @get('name').split(' ')[0]

class Xmpp.Collections.ContactsCollection extends Backbone.Collection
  model: Xmpp.Models.Contact

  initialize: ->
    _.bindAll(this)

    @friendsList = new Xmpp.Views.Contacts.ListView(collection: this, attributes: {title: 'chat.roster.friends', id: 'js-inactive-friends'})
    @friendsList.createListContainer()

    @activeList  = new Xmpp.Views.Contacts.ListView(collection: this, attributes: {title: 'chat.roster.chat-group', id: 'js-active-friends'})
    @activeList.setAsActiveChatGroup()

    @on("add", @appendContact)

  appendContact: (contact) ->
    @friendsList.appendContact(contact)

  moveToActiveList: (contact) ->
    @_switchContactBelongingList(@get(contact), @friendsList, @activeList)

  moveToInactiveList: (contact) ->
    if contact == 'all'
      _.each(@activeList.contactViews, (view) =>
        @_switchContactBelongingList(view.model, @activeList, @friendsList)
      )
    else
      @_switchContactBelongingList(@get(contact), @activeList, @friendsList)

  updateStatus: (response) ->
    @get(response.jid).set(message: response.status.message, status: response.status.status)

  udpateVcard: (response) ->
    @get(response.jid).set(name: response.vcard.name, avatar: response.vcard.avatar)

  _switchContactBelongingList: (contact, fromList, toList) ->
    if !contact?
      false

    fromList.detachContact(contact) && toList.appendContact(contact)

    true