package Customizer::CGI;
# $Id: CGI.pm,v 1.11 2001/01/03 08:20:37 tom Exp $
# customization interface for CGI
################################################################

use strict qw(vars);
use vars qw(@ISA @EXPORT);
use Exporter;

use CGI::QueryString;
#use CGI::Tools;
use Customizer::Base;
use Customizer::ItemCGI;
use Skelton;

@ISA = qw(Customizer::Base);
@EXPORT = qw(attributes);

attributes qw(input_skelton);

################################################################
sub initialize($)
{
    my $self = shift;

    $self->input_skelton(new Skelton)
	unless $self->input_skelton;
    
    $self->input_skelton->
	skelton(qq(<html><head><title>customizer</title></head>
		   <body>
		   <h1>customizer</h1>
		   <form action="<!--#macro cmd="ACTION_URL"-->" method="POST">
		   <!--#macro cmd="CONTENT" -->
		   <input type="hidden" name="command" value="save">
		   <hr>
		   <!--#macro cmd="INPUT_PASSWORD" -->
		   <hr>
		   <input type="submit" name="command" value="save">
		   <input type="reset" value="reset">
		   </form></body></html>));
    $self->SUPER::initialize;
}
sub CreateItem($%)
{
    my ($self, %assoc) = @_;

    return new Customizer::ItemCGI(%assoc);
}
sub SetMacros($)
{
    my $self = shift;
    
    my $url = $ENV{'REQUEST_URI'};
    $url =~ s/\?.*$//;
    $self->input_skelton->SetMacro("ACTION_URL", $url);

    my $content;
    for (@{$self->content}){
	$content .= sprintf("<h2>%s</h2>", $_->name);
	for (@{$_->content}){
	    next if $_->no_cgi;
	    $content .= $_->AsSelect;
	}
    }
    $self->input_skelton->SetMacro("CONTENT", $content);
    $self->input_skelton->SetMacro("INPUT_PASSWORD", qq(Password: <input type="password" name="password">))
	unless $self->input_skelton->hash->{'INPUT_PASSWORD'};
}

sub Input($)
{
    my $self = shift;

    $self->SetMacros;
    print $self->input_skelton->AsHTML;
    exit;
}
################
sub AsOutput($)
{
    my $self = shift;

    for (@{$self->content}){
	for (@{$_->content}){
	    my $tag = $_->name;
	    if ($_->no_cgi){
		my $var = $tag;
		$_->data($$var);
	    } else {
		$_->data(param(CGI::Tools::UrlEncode($tag)));
	    }
	}
    }
    $self->SUPER::AsOutput;
}    

sub Save($)
{
    my $self = shift;
    
    my $code = $self->AsOutput;
    
    $self->WriteToFile($code);
    
    my $filename = $self->filename;
    print "<h2>$filename</h2>";
    print "<pre>";
    print CGI::Tools::Escape($code);
    print "</pre>";
    print qq(<hr><a href="./">back</a>);
    
}
sub Do ($)
{
    my $self = shift;

    $self->PrintHTTPHeader();
    $self->Read;
    if (param('command') eq 'save'){
	$self->Save;
    } else {
	$self->Input;
    }
}

sub PrintHTTPHeader
{
    print "content-type: text/html\r\n\r\n";
}
1;
