class ApiChatsController < ApiController

  before_filter :api_signed_in_user, :check_session

  respond_to :json

  def create

    @chat_msg = ChatMessage.create(current_user, @music_session, params[:message], params[:channel], params[:client_id], @target_user, @lesson_session)

    respond_with_model(@chat_msg)
  end

  def index
    data = ChatMessage.index(current_user, params)
    @chats = data[0]
    @next = data[1]
    render "api_chats/index", :layout => nil
  end

  def check_session
    if params.has_key?(:music_session) || params[:channel] == 'session'
      @music_session = ActiveMusicSession.find(params[:music_session])
      if @music_session.nil?
        raise ArgumentError, 'specified session not found'
      end

      unless @music_session.access? current_user
        raise JamPermissionError, 'not allowed to join the specified session'
      end
    end

    if params.has_key?(:lesson_session)
      @lesson_session = LessonSession.find(params[:lesson_session])
      if @lesson_session.nil?
        raise ArgumentError, 'specified lesson session not found'
      end

      unless @lesson_session.access? current_user
        raise JamPermissionError, 'not allowed to join the specified lesson session'
      end

      @target_user = User.find(params[:target_user]) if params[:target_user]
    end

  end

end