Xmpp.Views.Contacts ||= {}

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

  events:
    'click .js-edit-status': (e) -> @editTextInput(e)
    'keypress .js-edit-status': (e) -> @confirmMyStatus(e)

    'click .js-edit-name': (e) -> @editTextInput(e)
    'keypress .js-edit-name': (e) -> @confirmMyName(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

  editTextInput: (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())

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

    $this = $(e.currentTarget)

    if ($this.val() == '')
      $this.removeClass('editing')
        .val(@model.get('jid'))
    else
      $this.removeClass('editing')

    $this.blur()
    App.Com.updateMyVcard(@_getName())

  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-edit-status').hasClass('empty')
      return ''
    else
      $('.js-edit-status').val()

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

  _getName: ->
    $('.js-edit-name').val()