package Web::App;

use strict;
use warnings;

use CGI;
use Web::App::Controller;
use Web::Dialog;
use Web::Page;

sub new {
	my ($class, $start_dialog, $url, $domain, $db) = @_;
	my $cgi = CGI->new;
	my $self = bless {
		url => 'http://'.$cgi->server_name.':'.$cgi->server_port.'/'.$url,
		dialogs => {},
		cgi => $cgi,
		domain => $domain,
		db => $db,
		controller => {},
	}, $class;
	my $path = $self->cgi->path_info || '/';

	$self->{path} = [split /\//, $path];
	$self->{dialog} = $self->path(1) || $start_dialog;
	$self->{params} = $self->path;
	
	shift @{$self->{params}};
	shift @{$self->{params}};

	return $self;
}

sub db { $_[0]->{db} }
sub domain { $_[0]->{domain} }
sub dialogs { wantarray ? values %{$_[0]->{dialogs}} : $_[0]->{dialogs} }
sub dialog { $_[0]->{dialogs}->{$_[0]->{dialog}} }
sub dialog_name { $_[0]->{dialog} }
sub start { $_[0]->{start} }
sub url { defined $_[1] ? $_[0]->{url}.'/'.$_[1] : $_[0]->{url} }
sub path { defined $_[1] ? $_[0]->{path}->[$_[1]] : $_[0]->{path} }
sub params { $_[0]->{params} }
sub cgi { $_[0]->{cgi} }

sub controller {
	my ($self, $page) = @_;

	$self->{controller} = Web::App::Controller->new($self, $page)
		if defined $page;
	
	return $self->{controller};
}

sub add_dialog {
	my ($self, $name, $package) = @_;
	
	$self->{dialogs}->{$name} = $package;
	
	return $self;
}

sub create_dialog {
	my ($self) = @_;
	
	return Web::Page->new(sub {
		my ($page) = @_;
		my $dialog = Web::Dialog->new($self->controller($page), $self,
									  $self->dialog, $self->params);

		$dialog->show;
	});
}

sub show {
	my ($self) = @_;
		
	$self->create_dialog->show;
	
	return $self;
}

1;
