Xmpp.Views.Tabbar ||= {}

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

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

    Backbone.Events.on('openChat', (chat) =>
      @hideCurrentChatWindow()
      @addOrSelect(chat)
    )

    Backbone.Events.on('closeChat', (chat) =>
      tab = _.find(@tabs, (_tab) =>
        _tab.model == chat
      )

      if tab
        @removeTab(tab)

        if tab == @activeTab
          App.Collections.contacts.moveToInactiveList('all')
          @openFirstTab()
    )

    Backbone.Events.on('removeContact', (contact) =>
      tab = _.find(@tabs, (_tab) =>
        _tab.model.get('withWhom') == contact
      )

      Backbone.Events.trigger('closeChat', tab.model) if tab
    )

    @tabs = []
    @activeTab = null
    @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()
    )

    @activeTab = tab
    @activeTab.setActive()
    @activeTab.showChat()

  hideCurrentChatWindow: ->
    if @activeTab
      App.debug 'zakryvam chat window'
      @activeTab.hideChat()

  openFirstTab: ->
    firstTab = @selectFirstTab()
    Backbone.Events.trigger('openChat', firstTab.model) if firstTab

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

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

  selectFirstTab: ->
    _.first(@tabs)

  isEmpty: ->
    _.isEmpty(@tabs)