class ApiController < ApplicationController

  @@log = Logging.logger[ApiController]

  # define common error handlers
  rescue_from 'JamRuby::StateError' do |exception|
    @exception = exception
    render "errors/state_error", :status => 400
  end
  rescue_from 'JamRuby::JamArgumentError' do |exception|
    @exception = exception
    render "errors/jam_argument_error", :status => 400
  end
  rescue_from 'JamRuby::PermissionError' do |exception|
    @exception = exception
    render "errors/permission_error", :status => 403
  end
  rescue_from 'ActiveRecord::RecordNotFound' do |exception|
    @@log.debug(exception)
    render :json => { :errors => { :resource => ["record not found"] } }, :status => 404
  end
  rescue_from 'PG::Error' do |exception|
    @@log.debug(exception)
    if exception.to_s.include? "duplicate key value violates unique constraint"
      render :json => { :errors => { :resource => ["resource already exists"] } }, :status => 409 # 409 = conflict
    else
      raise exception
    end
  end

  protected
    def auth_user
      unless current_user.id == params[:id]
        raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR
      end
      
      @user = User.find(params[:id])
    end

    def optional_auth_user
      if current_user.nil?
        @user = nil
      else
        auth_user
      end

    end
end