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 = []

    Backbone.Events.on('removeContact', @detachContact)

  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, (contact) =>
        @render(contact.render().el)
      )

    return this

  filter: (searchTerm) ->
    regex = new RegExp(searchTerm.trim(), 'i')
    _.each(@contactViews, (view) ->
      searchInAttributes = view.model.pick('jid', 'name', 'message')
      searchString = _.toArray(searchInAttributes).join(' ')
      found = (searchString.search(regex) != -1)

      if found then view.unhide() else view.hide()
    )

  reOrder: ->
    groupedByStatus = _.groupBy(@contactViews, (view) ->
      view.model.get('status')
    )

    sortedGroupNames = {
      online: groupedByStatus.online
      away: groupedByStatus.away
      offline: groupedByStatus.offline
    }

    sorted = _.map(sortedGroupNames, (group) ->
      _.sortBy(group, (view) ->
        view.model.get('name') || view.model.get('jid')
      )
    )

    @contactViews = _.flatten(sorted)
    @render()