#!/usr/bin/perl
use strict;
use lib qw (../..);
use vars qw /$BASE_DIR/;
use CGI;
$CGI::USE_PARAM_SEMICOLONS = 1;
$BASE_DIR = undef;
use lib::sql::DBH;
use lib::Exception;
use lib::PSP;
use lib::cgi::CGI;
use flo::Standard;
use flo::Record::Editor;
use flo::Record::Document;


try
{
    init();
    main();
}
catch
{
    use Data::Dumper;
    print "Content-Type: text/plain\n\n";
    print Dumper (shift);
};


sub init
{
    # read sites information to know which site to use
    my $mkdoc_base_dir = undef;
    if ($ENV{SCRIPT_FILENAME})
    {
        my @tmp = split /\//, $ENV{SCRIPT_FILENAME};
        pop @tmp;
        pop @tmp;
	pop @tmp;
        $mkdoc_base_dir = join '/', @tmp;
    }
    else
    {
        $mkdoc_base_dir = '../..';
    }
    
    my $VAR1 = undef;
    open FP, "<$mkdoc_base_dir/conf/sites.conf";
    my $data = join '', <FP>;
    close FP;
    eval $data;
    die ($@) if (defined $@ and $@);
    my $SITES = $VAR1;
 
    # set up the base dir and config dir
    my $server_name = lc ($ENV{SERVER_NAME}) or
	throw (new lib::Exception ( code => 'SERVER_NAME_UNDEFINED',
				    info => "\$ENV{SERVER_NAME} does not seem to be defined" ) );
    
    # retrieve base directory or throw an exception
    my $base_dir = $SITES->{$server_name} or
	throw (new lib::Exception ( code => 'CANNOT_FIND_BASE_DIR',
				    info => "Base directory does not seem to be set for $server_name" ) );
    
    $BASE_DIR = $base_dir;

    $lib::sql::DBH::ETERNAL = undef;
    $lib::sql::DBH::DBH     = undef;
    $lib::sql::DBH::ETERNAL = undef;
    $lib::sql::DBH::DBH     = undef;
    $lib::sql::Table::DATABASE = {};
    @lib::sql::Table::QUERY_STACK = ();
    $lib::sql::Table::LOADED = undef;
    $lib::cgi::CGI::CGI = undef;
     
    # initialize CGI, template and database objects
    $lib::PSP::BASE_DIR = $base_dir . '/templates';
    lib::sql::Table->load_state ($base_dir . '/su');
}


sub main
{
    # triggers the right method depending on the CGI parameters
    my $cgi = cgi;
    my $action = $cgi->param ('action') || 'list_editor';
    __PACKAGE__->$action();
}


sub list_editor
{
    my $cgi = cgi;
    my $cgix = $cgi->new;
    foreach ($cgix->param) { $cgix->delete ($_) }
    
    my $editor_table = table ('Editor');
    my $editor = $editor_table->search()->fetch_all();
    
    # computes the URI to add a new editor
    $cgix->param ('action', 'add_editor_form');
    my $New_Editor_URI = $cgix->self_url;    
    
    print $cgi->header;
    my $psp = new lib::PSP ( 'su2/list_editor.html', qw /editor New_Editor_URI/ );
    $psp->compile()->( editor => $editor,
		       New_Editor_URI => $New_Editor_URI );
}


sub add_editor_form
{
    my $class = shift;
    my $err = shift || {};
    my $cgi = cgi;
    my $document_table = table ('Document');
    my $document = $document_table->select ( sort => [ qw /Full_Path/ ] )->fetch_all;
    
    print $cgi->header;
    my $psp = new lib::PSP ( 'su2/add_editor_form.html', qw /document error cgi/ );
    $psp->compile()->( document => $document,
		       error    => $err,
                       cgi      => $cgi );
}


sub add_editor
{
    my $class = shift;
    my $cgi = cgi;
    my $err = {};
    my $editor_table = table ('Editor');
    my $login = $cgi->param ('Login');
    $login =~ s/^[^A-Za-z0-9]+//;
    $login =~ s/[^A-Za-z0-9]+$//;
    $cgi->param ('Login', $login);
    if (not defined $cgi->param ('Login')       or $cgi->param ('Login')      eq '')  { $err->{Null_Login} = 1       }
    if (not defined $cgi->param ('Password')    or $cgi->param ('Password')   eq '')  { $err->{Null_Password} = 1    }
    if (not defined $cgi->param ('Email')       or $cgi->param ('Email')      eq '')  { $err->{Null_Email} = 1       }
    if (not defined $cgi->param ('Family_Name') or $cgi->param ('Family_Name') eq '') { $err->{Null_Family_Name} = 1 }
    if (not defined $cgi->param ('Disabled')    or $cgi->param ('Disabled')   eq '')  { $err->{Null_Disabled} = 1    }
    if (defined $editor_table->get (Login => $cgi->param ('Login'))) { $err->{Login_Exists} = 1 }

    if (keys %{$err}) { $class->add_editor_form ($err) }
    else
    {
	$editor_table->insert ($cgi);
	my $editor = $editor_table->get ( Login => $cgi->param ('Login') );
	my $base_document_table = table ('Base_Document');

	foreach my $document_id ($cgi->param ('DocID'))
	{
	    $base_document_table->insert ( Editor_ID   => $editor->{ID},
					   Document_ID => $document_id );
	}
	list_editor();
    }
}


sub modify_editor_form
{
    my $class = shift;
    my $err = shift || {};
    my $cgi = cgi;
    
    my $document_table = table ('Document');
    my $editor_table   = table ('Editor');
    my $base_document_table = table ('Base_Document');
    
    my $document = $document_table->select ( sort => [ qw /Full_Path/ ] )->fetch_all;
    my $editor   = $editor_table->get ($cgi->param ('ID'));
    
    # find out which are the administrable documents
    my $administrable = {};
    my $query = $base_document_table->search ( Editor_ID => $editor->{ID} );
    while (my $h = $query->next)
    {
	$administrable->{$h->{Document_ID}} = 1;
    }
    foreach (@{$document})
    {
	$_->{Selected} = $administrable->{$_->{ID}};
    }
    
    my $default = {};
    foreach ($editor_table->cols) { $default->{$_} = $editor->{$_} || $cgi->param ($_) };
    
    print $cgi->header;
    my $psp = new lib::PSP ( 'su2/modify_editor_form.html', qw /document default error editor cgi/ );
    $psp->compile()->( document => $document,
		       default  => $default,
		       error    => $err,
		       editor   => $editor,
                       cgi      => $cgi );
}


sub modify_editor
{
    my $class = shift;
    my $cgi = cgi;
    my $err = {};
    my $editor_table = table ('Editor');
    
    if (not defined $cgi->param ('Password')    or $cgi->param ('Password')    eq '') { $err->{Null_Password} = 1    }
    if (not defined $cgi->param ('Email')       or $cgi->param ('Email')       eq '') { $err->{Null_Email} = 1       }
#    if (not defined $cgi->param ('First_Name')  or $cgi->param ('First_Name')  eq '') { $err->{Null_First_Name} = 1  }
    if (not defined $cgi->param ('Family_Name') or $cgi->param ('Family_Name') eq '') { $err->{Null_Family_Name} = 1 }
    if (not defined $cgi->param ('Disabled')    or $cgi->param ('Disabled')    eq '') { $err->{Null_Disabled} = 1    }
    
    if (keys %{$err}) { $class->modify_editor_form ($err) }
    else
    {
	$editor_table->modify ($cgi);
	my $editor = $editor_table->get ( Login => $cgi->param ('Login') );
	my $base_document_table = table ('Base_Document');
	$base_document_table->delete ( Editor_ID => $editor->{ID} );
	foreach my $document_id ($cgi->param ('DocID'))
	{
	    $base_document_table->insert ( Editor_ID   => $editor->{ID},
					   Document_ID => $document_id );
	}
	$class->list_editor();
    }
}


sub delete_editor_form
{
    my $class = shift;
    my $cgi = cgi;
    my $editor_table = table ('Editor');
    my $editor = $editor_table->get ($cgi->param ('ID'));

    my $cgix = $cgi->new;
    foreach ($cgix->param) { $cgix->delete ($_) }
    my $Cancel_URI = $cgix->self_url;
    
    print $cgi->header;
    my $psp = new lib::PSP ( 'su2/delete_editor_form.html', qw /editor Cancel_URI cgi/ );
    $psp->compile()->( editor => $editor,
		       Cancel_URI => $Cancel_URI,
                       cgi        => $cgi );
}


sub delete_editor
{
    my $class = shift;
    my $cgi = cgi;
    
    my $id = $cgi->param ('ID');

    if ($id == 1)
    {
	print "Content-Type: text/plain\n\n";
	print "Don't even try to think about this...";
    }
    else
    {
	my $document_table = table ('Document');
	my $base_document_table = table ('Base_Document');
	my $editor_table = table ('Editor');
	
	$editor_table->delete ( ID => $id );
	$base_document_table->delete ( Editor_ID => $id );
	$document_table->update ( { Editor_Created_ID => 1 }, { Editor_Created_ID => $id } );
	$document_table->update ( { Editor_Last_Modified_ID => 1 }, { Editor_Last_Modified_ID => $id } );
	$class->list_editor();
    }
}


1;







