Xmpp.Views.Contacts ||= {}

class Xmpp.Views.Contacts.ListView extends Backbone.View
  template: JST["backbone/templates/contacts/contact_list"]

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

    @el = '#' + @attributes['id']
    @title = I18n.t(@attributes['title'])

    @titleClass = @listClass = ''
    @activeGroup = false
    @contactViews = []

  createListContainer: ->
    $(@el).html(@template(title: @title, isActiveGroup: @activeGroup))

  appendContact: (contact) ->
    if @hasContact(contact)
      return false

    if @contactViews.length == 0
      @createListContainer()

    view =  new Xmpp.Views.Contacts.ContactView(model: contact, attributes: {listView: this})
    @contactViews.push view
    @render(view.render().el)

  detachContact: (contact) ->
    matchingView = @hasContact(contact)
    if matchingView
      @contactViews = _.without(@contactViews, matchingView)
      matchingView.remove()

      if @contactViews.length == 0
        $(@el).html('')

    return !!matchingView

  hasContact: (contact) ->
    _.find(@contactViews, (view) ->
      view.model == contact
    )

  setAsActiveChatGroup: ->
    @activeGroup = true

  render: (contactHtml) ->
    if (contactHtml?)
      $(@el).find('ul').append(contactHtml)
    else
      _.each(@contactViews, (i, contact) =>
        @render(contact.render().el)
      )

    return this