#
# requst_dispatcher.rb -- HTTPServer Class
#
# Author: IPR -- Internet Programming with Ruby -- writers
# Copyright (C) 2002 David Corbin
#
# $IPR:$
require 'webrick/httpserver'
require 'webrick/httputils'
require 'webrick/httpstatus'
require 'webrick/httprequest'
require 'webrick/httpresponse'
require 'webrick/httpservlet'
module WEBrick
	class RequestDispatcher
		class StringIO
			def initialize(input)
				@input = input
			end
			def gets(untilChar)
				newlinePos = @input.index(untilChar)
				if (newlinePos != nil)
					line =  @input.slice!(0..newlinePos)
				else
					line = @input
					@input = ""
				end
				return line
			end
			def read(n)
				if (n > @input.length)
					line = @input
					@input="";
					return line
				end
				return @input.slice!(1..n)
			end
		end
		def initialize(config,url,http_server)
			@config=config
			@url = url
			@http_server = http_server
		end
		def prepareRequest(request)
			url = @url
			if (url !~ /^\//)
				pathDir = request.path
				pathDir.sub!(%r|/.[^/]*$|,"")
				url = pathDir+"/"+url
			end
			return StringIO.new("GET #{url}\n\n")
		end
		def include(req,res)
			newRes = WEBrick::HTTPResponse.new(@config)
			req.parse(prepareRequest(req))
		    @http_server.service(req,newRes)
			res.body = res.body + newRes.body
		end
		def forward(req,res)
			res.body=""
			include(req,res)
		end
	end
end