package Catalyst::Plugin::Regions;

use strict;
use warnings;

our $VERSION = '0.01';

#@__PACKAGE__->mk_accessors('uuid');


=head1 NAME

portal::Plugin::regions; Subrequest to regions of a page

=head1 SYNOPSIS

   use Catalyst qw/	regions /;

=head1 DESCRIPTION

Let's you auto dispatch to other actions on a page and make the results
available for inserting into a template.

=head1 METHODS

This plugin defines the following methods.

=head2 prepare

Override prepare to setup all the regions for a give controller

=cut

sub prepare
{
	my $class	= shift @_;
	my $c		= $class->NEXT::prepare(@_);

	## Is this an action with a Region Attribute?
	return $c unless $c->action && exists $c->action->attributes->{Regions};
	
	## Okay, let's gather some needed information about the current action

	my $regions			= $c->action->attributes->{Regions}[0] || return $c;
	
	$c->log->dumper([$regions]);
	
	my @regions = split(',', $regions);
	
	

	$c->log->debug("Found a regioned action called: ".$c->action->reverse);	
	
	## And some info about the controller
	
	my $this_controller	= $c->controller;
	my $controller_name	= $this_controller->action_namespace;
	
	## Get any global configuration
	my %attributes		= %{$c->config->{regions} || {}};
	
	## Loop over each region and add it to the list for later dispatch
	
	foreach  my $region ( @regions )
	{
		$c->log->debug("Getting Region: $region ");
		
		my $action = $c->controller->action_for($region);  ##TODO, need to make sure this action is good.
		
		my $link = $c->uri_for( $region, @{$c->request->arguments} ) 
		 || $c->uri_for( $region, $c->request->captures ) 
		 || undef;

		$attributes{$controller_name}->{$action->reverse} = {
		
			action		=> sub { $c->controller->action_for('$region') },
			response	=> sub { $c->model('http')->get({link=>$link}) },
			
			link		=> $link,		
		};
	}
	
	## Keep this region list around
	$c->config->{regions} = \%attributes;

	return $c;
}


=head2 regions

Return an array of all regions for the given controller

=cut

sub regions
{
    my $c = shift;

	my $controller_name	= $c->controller->action_namespace;
	
	return $c->config->{regions}->{$controller_name};
}


=head2 finalize

Add all the regions to a response.

=cut

sub dispatch
{
	my $c = shift;
	
	$c->log->debug("Got Dispatch request for regioned action");
	
	my %region_names = %{$c->regions};
	
	foreach my $region ( keys %region_names )
	{
		$c->log->debug("Doing Region: ".$c->regions->{$region});
		
		my $friendly_name = join('', map { ucfirst($_) } split(/\/|_/,$region) );
		
		$c->log->debug("Got Name: $friendly_name");		
		
		$c->stash->{$friendly_name} = $c->regions->{$region};
	}

	return $c->NEXT::dispatch(@_);
}


=head1 AUTHOR

john napiorkowski

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
