Xmpp.Views.Tabbar ||= {}

class Xmpp.Views.Tabbar.TabbarView extends Backbone.View
  template: JST["backbone/templates/tabbar/tabbar"]
  el: $('#js-tabbar')

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

    @tabs = []
    @render()

  addOrSelect: (chat) ->
    tab = _.find(@tabs, (tab) ->
      tab.hasParticipants(chat.get('who'), chat.get('withWhom'))
    )

    if (!! tab)
      App.debug 'selecting existing tab'
    else
      App.debug 'adding new tab'
      tab = new Xmpp.Views.Tabbar.TabView(model: chat)
      @tabs.push tab
      $(@el).append(tab.render().el)

    _.each(@tabs, (tab) ->
      tab.setInactive()
    )

    tab.setActive().el

  removeTab: (tab) ->
    @tabs = _.without(@tabs, tab)

  render: ->
    $(@el).html('')
    return this