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
    @isClosingTab = false

    Backbone.Events.on('closeChat', (chat) =>
      if not @isClosingTab
        if chat == @model
          @destroy()
    )

    @model.get('who').on('change:name', @render)

  closeChat: ->
    # zatvorenie musi prebehnut ako prva akcia,
    # lebo zavisi na poradi a eventy mi nezarucia spravne poradie
    @destroy()

    @isClosingTab = true
    Backbone.Events.trigger('closeChat', @model)

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

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

  render: ->
    if (@model.get('isMultiChat'))
      $(@el).html(@template(
        who:       @model.get('who').firstname(),
        multiChat: true
      ))
    else
      $(@el).html(@template(
        who:       @model.get('who').firstname(),
        withWhom:  @model.get('withWhom').firstname(),
        multiChat: false
      ))
    return this

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

    @chatWindow.render()
    Backbone.Events.trigger('resizeWorkspace')

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

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

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

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

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

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

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