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
      )

      @closeTab(tab) 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()

  closeTab: (tab) ->
    @removeTab(tab)

    if tab == @activeTab
      firstTab = @selectFirstTab()
      if firstTab
        App.debug 'fire openChat'
        Backbone.Events.trigger('openChat', firstTab.model)
    #TODO: vybrat naposledy pouzity tab

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

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

  selectFirstTab: ->
    _.first(@tabs)