# -----------------------------------------------------------------------------
#
#   Copyright (c) 1999-2002 by Klaus Reger <K.Reger@wwwdb.org>
#
#   You may distribute under the terms of either the GNU General Public
#   License or the Artistic License, as specified in the Perl README file.
#
#   THIS IS BETA SOFTWARE!
#
#   THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
#   IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
#   WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
#   $Id: CreateAppRc_5.pl,v 1.5 2003/04/10 14:07:22 k_reger Exp $
#
# -----------------------------------------------------------------------------
# Program-Data
# -----------------------------------------------------------------------------
# Project  :
# System   :
# Program  :
# Module   : $RCSfile: CreateAppRc_5.pl,v $
# Version  : $Revision: 1.5 $
# Date     : $Date: 2003/04/10 14:07:22 $
# State    : $State: Exp $
#
# Description:
#   Generate plugins for this application
#
# -----------------------------------------------------------------------------
# Change-log (See at end of this file)
# $Log: CreateAppRc_5.pl,v $
# Revision 1.5  2003/04/10 14:07:22  k_reger
# - BUGFIX
#
# Revision 1.4  2002/11/19 15:30:02  k_reger
# - Array-Problem fixed
#
# Revision 1.3  2002/11/18 14:58:07  k_reger
# - Target-Db added
#
#
# --- Known Bugs -------------
# 
# --- TODO -------------------
# - generate variables, that show, which params are passed
# ----------------------------------------------------------------------------
use strict;
use vars qw($oSessionGL %hPluginDataMGL);

sub PreCreateForm ()
{
   my $cFoundSubs;
   my $cPerlSource = ();
   my $cPerlSourceFile;
   my $cSection;
   my $oConfigFile;
   my @lPlugins     = ();
   my @lResult      = ();

   my $cTable    = $oSessionGL->getState("CreateAppRc,DbTable");
   my $cDatabase = $oSessionGL->getState("CreateAppRc,Database") ||
	   &MyVal('DB', 'Database');

   &SetField("DbTable", $cTable);

   # this is the config-file, we work with
   $oConfigFile = ConfigFile->new
       (&GetAttr("BaseDir") . "/lib/WWWdb/Dyn/" .
        $cDatabase . "/". $cTable . ".rc",
        ReadOnly => 0);

   &MySetVal("Header", "Title",
             i18n(&MyVal("Header", "Title", "")) . " ($cTable)");
   &MySetVal("State Init", "Header",
             i18n(&MyVal("Header", "Title", "")));

   %hPluginDataMGL =
	   (
		# Procedure, Pre/Post, My, Description, parameters
		'PreCreateForm()' =>  [0, 0, i18n("Before the creation of any HTML"), ""],
		'PreDoAction()' =>    [0, 0, i18n("Before default Action"), ""],
		'FirstColumn()' =>    [1, 1, i18n("Modifying the navigation-column"), ""],
		'FormHeader($)' =>    [1, 1, i18n("Design of the form-header"), 
							   'my $cTitlePI = shift;'],
		'FormFooter($)' =>    [1, 1, i18n("Design of the form-footer"), 
							   'my $cTitlePI = shift;'],
		'TableHeader($)' =>   [1, 1, i18n("Design of the User-Header"), 
							   'my $cTitlePI = shift;'],
		'TableFooter($)' =>   [1, 1, i18n("Design of the User-Footer"), 
							   'my $cTitlePI = shift;'],
		'NoRecordFound()' =>  [0, 1, i18n("When no record could be found")],
		'ErrLabel($)' =>      [0, 1, i18n("Text for errors in input-data"), 
							   'my $cFieldPI = shift;'],
	);

   # scan all sections of config-file
   foreach $cSection ($oConfigFile->getSectionNames())
   {
      my $oSection;
      my $cEntry;

      $oSection = $oConfigFile->getSections()->Get("$cSection");

      # scan all entries of this section
      foreach $cEntry ($oSection->getEntryNames())
      {
         # this must be a button-definition
         if($cEntry =~ /^Btn(\w+)$/)
         {
            my $cName;
            my $oValue = $oSection->getEntries()->Get("$cEntry");

            $cName = $oValue->getValue();

            # ignore deactivated buttons
            next
                if $cName eq "-" or !$cName;

			$hPluginDataMGL{"Btn" . $1 . "()"} = 
				[1, 1, i18n("Action for Button: ").$1, ""],
			
         }
      }
   }

   # Plugins of Table
   $cTable = $oConfigFile->getValue("Data", "Table", undef);
   if(defined $cTable)
   {
	   $hPluginDataMGL{"Check_" . $cTable . "()"} = 
		   [0, 0, i18n("Check consistency for table: ").$cTable, ""];
	   $hPluginDataMGL{"Check_" . $cTable . "_EveryField()"} = 
		   [0, 0, i18n("Check consistency for table: ".$cTable), ""];
		   
      # Plugins of Entry-fields
      foreach (split ", ", $oConfigFile->getValue("Data", "UpdFields", undef))
      {
		  $hPluginDataMGL{"Check_" . $cTable . "_" . $_ . "()"} = 
			  [0, 0, i18n("Check consistency for field: ".$_), ""],
      }

      # Plugins of Query-fields
      foreach (split ", ", $oConfigFile->getValue("Data", "QryFields", undef))
      {
		  push @lPlugins, sprintf ('QryConv_%s($@)\\,%s %s',
								   $_,
								   i18n("Query-conversation for field "),
								   $_,
								   'my $cValuePI = shift; my %hRecordPI = @_;');
      }
   }

	   # Plugins of Entry-Fields
	   foreach (split ", ", $oConfigFile->getValue("Data", "ExtraFields", undef))
	   {
		   $hPluginDataMGL{"Check_" . $cTable . "_" . $_ . "()"} = 
			   [0, 0, i18n("Check consistency for field"), ""];
		   
	   }
   }

   foreach (keys %hPluginDataMGL)
   {
	   my @lRecord = @{$hPluginDataMGL{$_}};
	   
	   # Pre/Post - Plugin
	   if ($lRecord[0])
	   {
		   push @lPlugins, sprintf("Pre%s\\,%s (Pre);%s",
								   $_,
								   $lRecord[2],
								   $lRecord[3]);
		   
		   push @lPlugins, sprintf("Post%s\\,%s (Post);%s",
								   $_,
								   $lRecord[2],
								   $lRecord[3]);
	   }
	   
	   # My - Plugin
	   if ($lRecord[1])
	   {
		   push @lPlugins, sprintf("My%s\\,%s (My);%s",
								   $_,
								   $lRecord[2],
								   $lRecord[3]);
	   }
	   else
	   {
         push @lPlugins, sprintf("%s\\,%s;%s",
								 $_,
								 $lRecord[2],
								 $lRecord[3]);
	 }
	   
   }

   &MySetVal("Layout Field DefPlugins", "Values",
             join "\n", @lPlugins);

   unless(&GetAttr("LastBtn") eq "BtnSync")
   {

	   $cPerlSourceFile = (&GetAttr("BaseDir") . "/lib/WWWdb/Dyn/" .
						   $cDatabase . "/". $cTable . ".pl");

      if(-f $cPerlSourceFile)
      {
         # this is the config-file, we work with
         open SOURCE, "<" . $cPerlSourceFile
             or &Error(sprintf(i18n("can't open Plugin-Source %s!"),
                               $cPerlSourceFile));

         while (<SOURCE>)
         {
            # chomp;

            # skip the return-code for perl-modules (will be added later)
            next if /\s*1;\s*/;

            $cPerlSource .= $_; # . "\n";
         }

         close SOURCE;

         &SetField("Source", $cPerlSource);

      }

      &MySetVal("Layout Field DefPlugins", "Values",
                join "\n", @lPlugins);

      # &SetField("DefPlugins", $cFoundSubs);
   }

   &BtnSync();
}



sub MyBtnFinish ()
{
	my $cTable    = $oSessionGL->getState("CreateAppRc,DbTable");
	my $cDatabase = $oSessionGL->getState("CreateAppRc,Database") ||
		&MyVal('DB', 'Database');

	if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {
      &WriteSource();
	  
	  &Redirect(&GetAttr("SessionId"), 
				sprintf("WWWdb:Dyn:%s:%s", 
						$cDatabase,
						$cTable));
   }
}


sub MyBtnNext ()
{
   &MyBtnFinish();
}


sub MyBtnPrev ()
{
   print &Redirect(&GetAttr("SessionId"), "WWWdb:Wiz:CreateAppRc_4");
}


sub BtnSync()
{
   my $cSource;
   my %hSubs = ();

   $cSource = &GetField("Source");

   # get all subroutines in source
   foreach (split "\n", $cSource)
   {
      if(/sub\s+(\w+\(.*\))/)
      {
         $hSubs{$1} = "SRC";
         printf STDERR "SRC: $1\n";
      }
   }

   # get all selected fields
   foreach (split "\\\\,", &GetField("DefPlugins"))
   {
      if(defined($hSubs{$_}))
      {
         printf STDERR "SRC+SEL: $_\n";
         $hSubs{$_} = "SRC+SEL";
      }
      else
      {
         printf STDERR "SEL: $_\n";
         $hSubs{$_} = "SEL";
      }
   }


   foreach (keys %hSubs)
   {
      next
          unless $_;

      if($hSubs{$_} eq "SRC")
      {
         &SetField("DefPlugins", &GetField("DefPlugins") . "\\," . $_);
      }
      elsif($hSubs{$_} eq "SEL")
      {
		  (my $cProcName, my $cParam) = split ";", $_;

		  &SetField("Source", &GetField("Source") . <<EOF);

# ----------------------------------------------------------------
# Plugin for $cProcName
# ----------------------------------------------------------------
sub $cProcName
{
   $cParam

   return;
}


EOF


      }
   }

   return;
}




sub PostFirstColumn ()
{
   my $cResult = "";


   $cResult .= (br() x 2 .
                b(i18n("See also:")) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_0",
                                    i18n("Select Database"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_1",
                                    i18n("Select DB-table"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_2",
                                    i18n("Select DB-fields"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_2a",
                                    i18n("Field-order"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_3",
                                    i18n("Mode-Information"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_4",
                                    i18n("Field attributes"))) .
                li(&ResolveRefField("wwwdb://WWWdb:Wiz:CreateAppRc_5",
                                    i18n("Plugins")))
                );

   return small($cResult);

}

sub WriteSource()
{
   my $cPerlSource;

   # get the table-name, we generate the config-file for
   my $cTable = $oSessionGL->getState("CreateAppRc,DbTable");
   my $cDatabase = $oSessionGL->getState("CreateAppRc,Database") ||
	   &MyVal('DB', 'Database');

   my $cConfigDir = (&GetAttr("BaseDir") . 
					 "/lib/WWWdb/Dyn/" . 
					 $cDatabase . "/");

   $cPerlSource = &GetField("Source");

   $cPerlSource =~ s/\r//g;

   # add the return-code for perl-modules
   $cPerlSource .= "\n1;";


   my $cPerlSourceFile = ($cConfigDir . "/" . $cTable . ".pl");

   # this is the config-file, we work with
   open SOURCE, ">" . $cPerlSourceFile
       or &Error(sprintf(i18n("can't open Plugin-Source %s!"),
                         $cPerlSourceFile));

   print SOURCE $cPerlSource;

   close SOURCE;

}

1;
