package Customizer::Base;

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

use ObjectTemplate;
use File::Copy;
use Exporter;
use Input;

@ISA = qw(ObjectTemplate);
@EXPORT = qw(attributes);

attributes qw(content name number is_root filename cgi child_number);
#	      used_classes);

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

    $self->content([]) unless $self->content;
#    $self->used_classes([]) unless $self->content;
    $self->filename('customize.ph') unless $self->filename;
    $self->child_number(0);
    $self->SUPER::initialize;
}
sub CreateItem($%)
{
    my ($self, %assoc) = @_;

    return new Customizer::Item(%assoc);
}
sub AddItem($%)
{
    my ($self, %assoc) = @_;

    my $item = $self->CreateItem(%assoc);
    $self->child_number($self->child_number+1);
    $item->number($self->child_number);
    push(@{$self->content}, $item);
}
sub Add($$)
{
    my ($self, $cust) = @_;
    $self->child_number($self->child_number+1);
    $cust->number($self->child_number);

    push(@{$self->content}, $cust);
}
sub Input($)
{
    die "should be overriden";
}

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

    sprintf("%d: %s\n", $self->number, $self->name);
}
sub AsOutput($)
{
    my $self = shift;

    my $code;
#    for (@{$self->used_classes}){
#	$code .= "use $_;\n";
#    }
    for (@{$self->content}){
	$code .= "\# " . ($_->name) . "\n";
	for (@{$_->content}){
	    my $data = $_->data;
	    # escape for security
	    $data =~ s/\\/\\\\/g;
#	    $data =~ s/`/\\`/g;
	    $data =~ s/'/\\'/g;
	    
	    $code .= "\$" . $_->name . " = ";
	    if ($_->type eq 'int' || $_->type eq 'bool'){
		$code .= $data || 0;
	    } else {
		$code .= sprintf("'%s'", $data);
	    }
	    $code .= ";\n";
	}
    }
    $code .= "1;\n";
    return $code;
}

sub Save ($)
{
    my $self = shift;
    my $filename = $self->filename;

    copy($filename, "$filename-bak");

    $self->WriteToFile($self->AsOutput);
}

sub WriteToFile($$)
{
    my ($self, $code) = @_;

#    return;
    my $filename = $self->filename;
    open(F, ">$filename") || die $filename;
    print F $code;
    close F;
}
sub GetItem($$)
{
    my ($self, $name) = @_;

    for (@{$self->content}){
	for (@{$_->content}){
	    if ($name eq $_->name){
		return $_;
	    }
	}
    }
    die "no such item: $name";
}
sub Read($)
{
    my $self = shift;
    require $self->filename
	if -f $self->filename;

    # 既存のデータをセット
    for (@{$self->content}){
	for (@{$_->content}){
	    #print $_->name;
	    my $name = $_->name;

	    # require required classes
	    my $class;
	    if ($name =~ /::/){
		$name =~ /(.*)::[^:]*$/;
		$class = $1;
#		$class =~ s!::!/!g;
	    } else {
		$class = $name;
	    }
#	    warn times, " class: $class";
#	    require "$class.pm";
	    my $code =  "use $class;";
	    eval $code;
	    if ($@){
		die $!;
	    }
#	    warn times;

	    $_->data($$name);
	}
    }
}
    
sub Do ($)
{
    die "should be overriden";
}
 
1;
