use strict;

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

   # get the table-name, we generate the config-file for
   $cTable = $oSessionGL->getState("CreateAppRc,DbTable");

   &SetField("DbTable", $cTable);

   $oConfigFile = ConfigFile->new
       (&GetAttr("BaseDir") . "/lib/WWWdb/tmp/" .
        $cTable . ".rc",
        ReadOnly => 0);

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

   @lPluginData =
       # Rocedure, Pre/Post, My, Description
       (
        ['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")],
        ['FormFooter($)',    1, 1, i18n("Design of the form-footer")],
        ['TableHeader($)',   1, 1, i18n("Design of the User-Header")],
        ['TableFooter($)',   1, 1, i18n("Design of the User-Footer")],
        ['NoRecordFound()',  0, 1, i18n("When no record could be found")],
        ['ErrLabel()',       0, 1, i18n("Text for errors in input-data")],
        );

   foreach (@lPluginData)
   {
      # Pre/Post - Plugin
      if ($_->[1])
      {
         push @lPlugins, "Pre" . $_->[0] . "\\," . $_->[3] . " (Pre)";
         push @lPlugins, "Post" . $_->[0] . "\\," . $_->[3] . " (Post)";
      }

      # My - Plugin
      if ($_->[1])
      {
         push @lPlugins, "My" . $_->[0] . "\\," . $_->[3] . " (My)";
      }
      else
      {
         push @lPlugins, $_->[0] . "\\," . $_->[3];
      }

   }

   # 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;

            push @lPlugins, ("PreBtn" . $1 . "()\\," .
                             i18n("Action for Button ")  . "$cName (Pre)");
            push @lPlugins, ("PostBtn" . $1 . "()\\," .
                             i18n("Action for Button ")  . "$cName (Post)");
            push @lPlugins, ("MyBtn" .   $1 . "()\\," .
                             i18n("Action for Button ") . "$cName (My)");

         }
      }
   }

   # Plugins of Table
   $cTable = $oConfigFile->getValue("Data", "Table", undef);
   if(defined $cTable)
   {
      push @lPlugins, ("Check_" . $cTable . "()\\," .
                       i18n("Check consistency for table")  . " $cTable");
      push @lPlugins, ("Check_" . $cTable . "_EveryField()\\," .
                       i18n("Field-check for every field of table ")  . " $cTable");

      # Plugins of Entry-fields
      foreach (split ", ", $oConfigFile->getValue("Data", "UpdFields", undef))
      {
         push @lPlugins, ("Check_" . $cTable . "_" . $_ . "()\\," .
                          i18n("Check consistency for field ")  . " $_");

      }

      # Plugins of Query-fields
      foreach (split ", ", $oConfigFile->getValue("Data", "QryFields", undef))
      {
         push @lPlugins, ("QryConv_" . $_ . "()\\," .
                          i18n("Query-conversation for field ")  . " $_");

      }
   }

   # Plugins of Entry-Fields
   foreach (split ", ", $oConfigFile->getValue("Data", "ExtraFields", undef))
   {
      push @lPlugins, ("Check_" . $cTable . "_" . $_ . "()\\," .
                       i18n("Check consistency for field ")  . " $_");

   }

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

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

      $cPerlSourceFile = (&GetAttr("BaseDir") . "/lib/WWWdb/tmp/" .
                          $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 ()
{
   if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {
      &WriteSource();
      &Redirect(&GetAttr("SessionId"), "WWWdb:tmp:" . GetField("DbTable"));
   }
}


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")
      {
         &SetField("Source", &GetField("Source") . <<EOF);

# ----------------------------------------------------------------
# Plugin for $_
sub $_
{

   return;
}


EOF


      }
   }

   return;
}




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


   $cResult .= (br() x 2 .
                b(i18n("See also:")) .
                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")))
                );

   return small($cResult);

}

sub WriteSource()
{
   my $cTable;
   my $cPerlSource;

   # get the table-name, we generate the config-file for
   $cTable = $oSessionGL->getState("CreateAppRc,DbTable");

   $cPerlSource = &GetField("Source");

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

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


   my $cPerlSourceFile = (&GetAttr("BaseDir") . "/lib/WWWdb/tmp/" .
                          $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;


