package CGI::Application::Plugin::PathInfoFixer;

use strict;
use Carp;
our $VERSION = '0.01';
use base qw(Exporter);

sub import{
	my $caller = scalar(caller);
    $caller->add_callback('prerun',\&_pathinfofixer_prerun);
	goto &Exporter::import;
}

sub _pathinfofixer{
	my $self = shift;
	my $q = $self->query;
	
	#make new path_info
	my $path_info='/'.$self->start_mode;
	if($self->param('CGIAPP_DISPATCH_PATH')){
		$path_info = '/'.lc $self->param('CGIAPP_DISPATCH_PATH') . $path_info;
	}

	my $location = $q->url();
	$location .= $path_info;
	$location .= '?' . $q->query_string if $q->query_string;

	$self->header_type('redirect');
	$self->header_props(-url=>$location);
	return 1;
}

sub _pathinfofixer_prerun{
	my $self = shift;
	my $q = $self->query;
	
	# do not redirect in POST
	return unless(lc $q->request_method eq "get");
	
	# check path_info
	my $path_info = $q->path_info;
	my $dispath_path = lc $self->param('CGIAPP_DISPATCH_PATH');
	$path_info =~ s!^/($dispath_path)*/*!!ie;
	return if(length($path_info) > 0);
	
	# The eval may fail, but we don't care
	eval {
		$self->run_modes('_pathinfofixer'=>\&_pathinfofixer);
		$self->prerun_mode('_pathinfofixer');
	};
	
	return 1;
}

1;

