require 'rest'

module RestColores
  class Application
    ["positions"].each do |base_path|
      get "/#{base_path}/:id/requirements" do
        position = get_position(params["id"])
        
        if (position.nil?)
          error 400, "Position does not exist"
        else
          conditionals = RestColores::Models::Conditional.where(position: position.id)
          error 400, "No Conditionals for Position [#{position.name}] exist" if conditionals.nil? || conditionals.length == 0
          conditionals.as_json
        end
      end
      
      post "/#{base_path}/:id/requirements" do
        position = get_position(params["id"])
        
        if (position.nil?)
          error 400, "Position does not exist"
        else
          @request_body[:position] = position
          conditional = RestColores::Models::Conditional.new @request_body
          
          if conditional.save
            headers \
              "Location" => request.host_with_port + "/#{base_path}/#{position.id}/requirements"
            status 201
          else
            error 400, ["Could not save Conditional"] + conditional.errors.full_messages
          end
        end
      end
    end
  end
end
