class Api::DynamicApiController < ApiController
  before_filter :restrict_access, :valid_per_page

  def index
    if params[:resources].to_s == 'hydro_establishments_hydro_routes'
      items = []
      HydroEstablishment.all.each{|he| he.hydro_routes.each{|hr| items << { hydro_establishment_id: he.id, hydro_route_id: hr.id } }}
    else
      model = params[:resources].to_s.singularize.camelize.constantize
      q = model.search(params[:q])
      items = q.result.paginate(page: params[:page], per_page: params[:per_page])
    end
    respond_to do |format|
      format.json { render json: items }
      format.xml { render xml: items }
    end
  end

  private
    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
        ApiKey.exists?(access_token: token)
      end
    end

    def valid_per_page
      unless params[:per_page].blank?
        params[:per_page] = 100 if params[:per_page].to_i > 100
      end
    end
end
