Xmpp.Views.Tabbar ||= {}

class Xmpp.Views.Tabbar.TabView extends Backbone.View
  template: JST["backbone/templates/tabbar/tab"]
  tagName: 'div'
  className: 'tab'

  events:
    'click .js-close': 'closeChat'
    'click a div': 'switchChatWindow'

  initialize: () ->
    _.bindAll(this)
    @active = false

  setActive: ->
    $(@el).addClass('active')
    @active = true
    @render()

  setInactive: ->
    $(@el).removeClass('active')
    @active = false
    @render()

  render: ->
    $(@el).html(@template(
      who:      @model.get('who').firstname(),
      withWhom: @model.get('withWhom').firstname()
    ))
    return this

  showChat: ->
    if !@chatWindow
      @chatWindow = new Xmpp.Views.Chat.WindowView(attributes: {tab: this})
      App.debug 'zobrazujem NOVY chat window'
    else
      App.debug 'zobrazujem EXISTUJUCI chat window'

    @chatWindow.render()

  destroy: ->
    App.debug 'destroy chatWindow and tab'
    if @active
      @chatWindow.remove()
    @remove()

  hideChat: ->
    if @chatWindow
      @chatWindow.hide();

  closeChat: ->
    @destroy()
    Backbone.Events.trigger('closeChat', this, @model)

  hasParticipants: (who, withWhom) ->
    @model && @model.get('who') == who && @model.get('withWhom') == withWhom

  switchChatWindow: ->
    Backbone.Events.trigger('openChat', @model)

  getOwner: ->
    @model.get('who')

  getChatId: ->
    @model.get('chatId')

  getAttendant: ->
    @model.get('withWhom')