Xmpp.Views.Contacts ||= {}

class Xmpp.Views.Contacts.MeView extends Backbone.View
  template: JST["backbone/templates/contacts/me"]
  el: $('#js-me')

  events:
    'click .js-click-edit': (e) -> @editMyStatus(e)
    'keypress .js-click-edit': (e) -> @confirmMyStatus(e)
    'click .js-change-state': (e) -> @openChangeState(e)
    'click .js-state-clickable': (e) -> @confirmChangeState(e)

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

    @model.on('change', @updateContact, this)

  updateContact: (me) ->
    @model = me
    @render()

  render: ->
    contact = @model.toJSON()
    $(@el).html(@template(contact))
    this

  editMyStatus: (e) ->
    $this = $(e.currentTarget)

    if ($this.hasClass('empty'))
      $this.val('')

    if (! $this.hasClass('editing'))
      $this.removeClass('empty')
           .addClass('editing')

  confirmMyStatus: (e) ->
    if (e.which != 13 && e.which != 10)
      return

    $this = $(e.currentTarget)

    if ($this.val() == '')
      $this.removeClass('editing')
        .addClass('empty')
        .val(I18n.t('chat.roster.change_status_msg'))
    else
      $this.removeClass('editing')

    $this.blur()
    App.Com.updateMyStatus(@_getStatusMessage(), @_getState())

  openChangeState: (e) ->
    $this = $(e.currentTarget)

    $this.addClass('editing')
         .find('.hidden').removeClass('hidden')

    $('.rolldown').removeClass('js-change-state')

  confirmChangeState: (e) ->
    $this = $(e.currentTarget)

    $('.rolldown').removeClass('editing')
      .addClass('js-change-state')
      .children().addClass('hidden')

    $('.rolldown').find('a').removeClass('active')

    $this.removeClass('hidden')
      .find('a').addClass('active')

    App.Com.updateMyStatus(@_getStatusMessage(), @_getState())

  _getStatusMessage: ->
    if $('.js-click-edit').hasClass('empty')
      return ''
    else
      $('.js-click-edit').val()

  _getState: ->
    $('.js-state-clickable:not(.hidden)').data('state')