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

  defaults:
    jid: ''
    preferredJid: null
    name: ''
    status: 'offline'
    message: ''
    avatar: 'assets/avatar.png'
    belongsTo: []
    usingMyApp: false

  initialize: ->
    _.bindAll(this)

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

    @set('id', @get('jid'))

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

  setUsingMyApp: ->
    @set('usingMyApp', true)

  setPreferredResource: (jid) ->
    @set('preferredJid', jid)

  getPreferredResource: ->
    @get('preferredJid') || @get('jid')

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)
    @on('change:belongsTo', @mergeContacts)

    Backbone.Events.on('openChat', (chat) =>
      @moveToInactiveList('all')
#      App.debug chat
      @moveToActiveList(chat.get('withWhom'))
    )

    Backbone.Events.on('closeChat', (chat) =>
      @moveToInactiveList('all')
    )

  appendContact: (contact) ->
    App.debug ['apppend', contact]
    @friendsList.appendContact(contact)

  mergeContacts: (contact) ->
    App.debug ['merging contacts', contact]
    #TODO: ak ten isty clovek je vo viacerych rosteroch, treba nastavit spravne belongsTo

    existingContact = @get(contact.get('id'))
    if existingContact?
      alreadyBelongsTo = existingContact.get('belongsTo')
      willBelongTo = contact.get('belongsTo')
      existingContact.set(belongsTo: _.union(alreadyBelongsTo, willBelongTo))
    else
      @add(contact)

  moveToActiveList: (contacts) ->
    App.debug ['move to active list', contacts];
    contacts = [contacts] unless _.isArray(contacts)

    _.each(contacts, (contact) =>
      @_switchContactBelongingList(@get(contact), @friendsList, @activeList) && @activeList.reOrder()
    )

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

  updateStatus: (response) ->
    contact = @get(response.jid)
    return unless contact

    contact.set(message: response.status.message, status: response.status.status)
    if response.status.status == 'offline'
      contact.setPreferredResource(null)

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

  subscriptionChanged: (newSubscription) ->
    if (newSubscription.action == 'subscribed')
      App.debug ['subscribed', newSubscription]

      newContact = new Xmpp.Models.Contact(
        id: newSubscription.jid
        jid: newSubscription.jid
        belongsTo: [newSubscription.belongsTo]
      )
      @mergeContacts(newContact)
    else if (newSubscription.action == 'unsubscribed')
      # TODO: show info and ask if user want to remove him from roster
      App.debug ['unsubscribed', newSubscription]

      contact = @get(newSubscription.jid)
      App.Com.removeContactRemote(contact.get('jid'), newSubscription.belongsTo)

      nowBelongsTo = _.without(contact.get('belongsTo'), newSubscription.belongsTo)
      if (nowBelongsTo.length == 0)
        Backbone.Events.trigger('removeContact', contact)
        @remove(contact)

    # ignore 'unsubscribe' type of action

  # toto sem asi nepatri, ale asi do views. Nic to v skutocnosti nerobi s modelmi.
  filter: (searchTerm) ->
    @friendsList.filter(searchTerm)
    @activeList.filter(searchTerm)

  findByJid: (jid) ->
    @get(jid)

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

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

    true