module JamRuby
  class ChatMessage < ActiveRecord::Base
    include HtmlSanitize
    html_sanitize strict: [:message]

    self.table_name = 'chat_messages'
    self.primary_key = 'id'

    default_scope order('created_at DESC')

    attr_accessible :user_id, :message, :music_session_id

    belongs_to :user
    belongs_to :music_session

    validates :user, presence: true
    validates :message, length: {minimum: 1, maximum: 255}, no_profanity: true

    class << self

      @@mq_router = MQRouter.new
      @@message_factory = MessageFactory.new

      def index(user, params = {})
        limit = params[:limit]
        limit ||= 20
        limit = limit.to_i

        start = params[:start].presence
        start = start.to_i || 0

        music_session_id = params[:music_session]

        query = ChatMessage.where('music_session_id = ?', music_session_id)
                           .offset(start).limit(limit)

        if query.length == 0
          [query, nil]
        elsif query.length < limit
          [query, nil]
        else
          [query, start + limit]
        end
      end

      def send_chat_msg(music_session, chat_msg, user, client_id)
        msg = @@message_factory.chat_message(
            music_session.id,
            user.name,
            user.id,
            chat_msg.message,
            chat_msg.id,
            chat_msg.created_at.utc.iso8601
        )

        @@mq_router.server_publish_to_session(music_session, msg, sender = {:client_id => client_id})
      end

    end

  end
end