Xmpp.Views.Contacts ||= {}

class Xmpp.Views.Contacts.ContactView extends Backbone.View
  template: JST["backbone/templates/contacts/contact"]
  tagName: 'li'
  className: 'clear user'

  events:
    'click .invite': 'inviteToMultichat'
    'click .chat': 'newMultiChat'
    'click': 'startChat'

  initialize: () ->
    _.bindAll(this)

#    Patrim nejakemu zoznamu
    @parentList = @attributes['listView']

    @model.on('change', @updateContact)
    @model.on('change:status', => @parentList.reOrder())

  updateContact: (contact) ->
    @model = contact
    @render()

  hide: ->
    $(@el).hide()

  unhide: ->
    $(@el).show()

  render: ->
    contact = @model.toJSON()
    $(@el).html(@template(contact))
    return this

  belongsToActiveList: ->
    @parentList.activeGroup == true

  startChat: ->
    if @belongsToActiveList()
      return

    who      = App.Models.me
    withWhom = @model

    App.debug ['opening chat with: ', who.get('jid'), withWhom.get('jid')]

    chat = App.Collections.chats.find(who, withWhom)
    if (! chat)
      App.debug ['not found in opened chats, creating new']
      chat = new Xmpp.Models.Chat(who: who, withWhom: withWhom)
      App.Collections.chats.add(chat)

    Backbone.Events.trigger('openChat', chat)

  inviteToMultichat: (e) ->
    e.stopPropagation();
    App.debug 'iniviting to multichat'

  newMultiChat: (e) ->
    e.stopPropagation();
    App.debug 'new multichat'
    withWhom = @model

    newChat = new Xmpp.Models.Chat(isMultiChat: true);
    newChat.set('who', App.Models.me);
    newChat.appendWithWhom(withWhom);

    App.Com.openNewMultiChat(App.Models.me, withWhom, newChat)

  openChatById: (chatId) ->
    chat = App.Collections.chats.findById(chatId)