require 'openid/errors'

module OpenID
	# Response is a hash with a modified constructor to pretty things a little
	class Response < Hash
		# Takes a hash, which becomes the contents of the Response object	
		def initialize(attr_hash)
			update(attr_hash)
		end
	end #class Response
	# Creates a Response object signaling a redirect to url.
	def redirect(url)
		return Response.new('code'=>302, 'redirect_url'=>url.to_s)
	end
	# Creates a response object signaling a plaintext response.
	def response_page(body)
		return Response.new('code'=>200, 'content_type'=>'text/plain', 'body'=>body)
	end
	# Creates a response object signaling a plaintext error.
	def error_page(body)
		return Response.new('code'=>400, 'content_type'=>'text/plain', 'body'=>body)
	end
	
	# Request objects are used by both the consumer and server APIs to signal
	# and represent various HTTP requests.
	
	class Request
		attr_reader :args, :http_method, :authentication
		attr_writer :args, :http_method
		# args is a hash of HTTP arguments.
		# http_method should be set to "POST" or "GET"
		# authentication is an unused passthrough field that will remain attatched
		# to the request.
		# A NoOpenIDArgs exception will be raised if args contains no openid.*
		# arguments.
		def initialize(args, http_method, authentication=nil)
			@args = args
			@http_method = http_method.upcase
			@authentication = authentication
			
			@args.each_key { |key|
				return if key.index('openid.') == 0
			}
			raise NoOpenIDArgs
		end
		# The preferred method for getting OpenID args out of the request.
		# Raises a ProtoclError if the argument does not exist.
		def [](key)
			result = get(key)
			if result == nil
				if key == 'trust_root'
					return self['return_to']
				else
					raise ProtocolError, "Query argument #{key} not found", caller
				end
			end
			return result
		end
		
		def get(key, default=nil)
			return @args.fetch('openid.' + key, default)
		end
	
	end #class Request
end #module OpenID
