Xmpp.Views.Chat ||= {}

class Xmpp.Views.Chat.MessageView extends Backbone.View
  template: JST["backbone/templates/chat/message"]
  className: 'message-box'

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

    @user = parts.user
    @dateSent = parts.date
    @fromMe = parts.fromMe
    @message = parts.message

  render: ->
    $(@el).html(@template(username: @user.get('name'), avatar: @user.get('avatar'), date: @formatTime(), message: @message))
    if @fromMe
      $(@el).addClass('me')

    return this

  formatTime:  ->
    nowDate = new Date()
    if (nowDate.getDate() != @dateSent.getDate() &&
        nowDate.getMonth() != @dateSent.getMonth() &&
        nowDate.getFullYear() != @dateSent.getFullYear())
      return @dateSent.getFullYear() + '/' + @_padDate((@dateSent.getMonth()+1)) + '/' + @_padDate(@dateSent.getDate()) +
        ' @ ' + @_padDate(@dateSent.getHours()) + ':' + @_padDate(@dateSent.getMinutes())

    return @_padDate(@dateSent.getHours()) + ':' + @_padDate(@dateSent.getMinutes())

  _padDate: (number) ->
    if number < 10
      '0' + number
    else
      number