use strict;

sub PreCreateForm ()
{
   my $cRecord;
   my $pDbHdl;
   my $pStmtHdl;
   my @lResult      = ();
   my @lExtraFields = ();
   my $cTable;
   my @lFields;
   my $oConfigFileTmp;
   my $oConfigFile;
   my $lAtt;
   my $oDbHandle;
   my $oStmtHdl;
   my $iCnt;
   my $lValue;

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

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

   # this is the temporary config-file for the actual HTML-page
   $oConfigFileTmp = ConfigFile->new
       ($oSessionGL->getState("CreateAppRc,ConfigFile"),
        ReadOnly => 0);

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

   # this button is for deletion of a field
   if(&GetAttr("LastBtn") =~ /^BtnWRK_(.*)$/)
   {
      &MyBtnWRK_($1)
          unless $1 eq "New_Field";
   }

   # This are the fields in the title of the table
   my @lTblHdrAtts =
       (["LBL", i18n("Name of the database-field"), "+2.+0.0" ],
        ["TXT", i18n("Text of Label"),              "+0.+1.0" ],
        ["TYP", i18n("Type of input-field"),        "+0.+1.0" ],
        ["SIZ", i18n("Length of input-field " .
                     "(If existing)"),              "+0.+1.0" ],
        ["UPD", i18n("Update- mode"),               "+0.+1.0" ],
        ["QRY", i18n("Query- mode"),                "+0.+1.0" ],
        ["IDX", i18n("Index- field"),               "+0.+1.0" ]);

   foreach $lAtt (@lTblHdrAtts)
   {
      $oConfigFileTmp->CreateSectionAndEntries
          (["Layout Label $lAtt->[0]",
            [["Text"   => $lAtt->[1]],
             ["Pos"    => $lAtt->[2]],
             ["Align"  => "Center"],
             ["Bold"   => "Yes"]]]);

   }

   $oConfigFileTmp->setValue("Layout Label Ruler1",
                             "Text", "<HR>");

   $oDbHandle = &GetAttr("DbHandle");

   if($cTable ne "UserFormat")
   {
      # this is a trick to find all field-names of a table
      $oStmtHdl = $oDbHandle->prepare("SELECT * FROM $cTable WHERE 0 = 1")
              or die "Can't prepare SELECT * FROM $cTable\n";
      $oStmtHdl->execute()
          or die("Can't get the fields of table $cTable\n");

      $iCnt = 0;

      # append field-names
      foreach (@{$oStmtHdl->{NAME}})
      {
         my $cBackground = $iCnt % 2? "#eeeeee": "#ffffff";
         my $bInUpdate   = 1;
         my $bInQuery    = 1;
         my $bInIndex    = !$iCnt;
         my @lWork;
         my $cWork;
         my $cType;
         my $cLabel;
         my $cSize;

         push @lFields, $_;

         # Create a nicer label
         $cLabel = "$_:";
         $cLabel =~ s/[-_]/ /g;

         $cLabel = $oConfigFile->getValue("Layout Label $_",
                                          "Text",
                                          $cLabel);

         $cType  = $oConfigFile->getValue("Layout Field $_",
                                          "Type",
                                          "Text");

         # Get the correct Size-Info
         $cSize = undef;

         if($cType eq "Text")
         {
            $cSize  = $oConfigFile->getValue("Layout Field $_",
                                             "Size",
                                             "40");

         }
         elsif($cType eq "Area")
         {
            $cSize  = sprintf("%dx%d",
                              $oConfigFile->getValue("Layout Field $_",
                                                     "Size",
                                                     "40"),
                              $oConfigFile->getValue("Layout Field $_",
                                                     "Rows",
                                                     "3"));
         }


         # Check if this field is updateable
         @lWork = split ", ", $oConfigFile->getValue("Data", "UpdFields", "");

         if (@lWork)
         {
            $bInUpdate = 0;

            foreach $cWork (@lWork)
            {
               $bInUpdate = 1
                   if ($cWork eq $_)
            }
         }

         # Check if this field is queryable
         @lWork = split ", ", $oConfigFile->getValue("Data", "QryFields", "");

         if (@lWork)
         {
            $bInQuery = 0;

            foreach $cWork (@lWork)
            {
               $bInQuery = 1
                   if ($cWork eq $_)
            }
         }

         # Check if this field is in index
         @lWork = split ", ", $oConfigFile->getValue("Data", "IdField", "");

         if (@lWork)
         {
            $bInIndex = 0;

            foreach $cWork (@lWork)
            {
               $bInIndex = 1
                   if ($cWork eq $_)
            }
         }

         $oConfigFileTmp->CreateSectionAndEntries
             (["Layout Label $_",
               [["Pos"     => "+1.+0.0"],
                ["Text"    => "$_:   "],
                ["Align"   => "Right"],
                ["Bold"    => "Yes"],
                ["BgColor" => $cBackground]]]);


         # the attributes for each field
         foreach $lAtt (["TXT", "Text",        $cLabel,
                         [["Size"      => "20"]]],
                        ["TYP", "Select",      $cType,
                         [["Values"    =>
                           (join "\n", ("Text\\," . i18n("Text"),
                                        "Area\\," . i18n("Area"),
                                        "Label\\," . i18n("Label"),
                                        "Hidden\\," . i18n("Hidden"),
                                        "\\," . i18n("Label-Only"),
                                        "Password\\," . i18n("Other"),
                                        "Btn\\," . i18n("Other"),
                                        "Ref\\," . i18n("Other"),
                                        "Checkbutton\\," . i18n("Other"),
                                        "Select\\," . i18n("Other"),
                                        "Radio\\," . i18n("Other")))]]],
                        ["SIZ", "Text",        $cSize,
                         [["MustMatch" => q(^((\d+)(x(\d+))?)?$)],
                          ["Size"      => "6"]]],
                        ["UPD", "Checkbutton", $bInUpdate],
                        ["QRY", "Checkbutton", $bInQuery],
                        ["IDX", "Checkbutton", $bInIndex])
         {

            # the single attributes
            foreach $lValue (["Text",    ""],
                             ["Pos",     "+0.+1.0"],
                             ["Type",    "$lAtt->[1]"],
                             ["Align",   "Center"],
                             ["BgColor", $cBackground])
            {

               $oConfigFileTmp->setValue("Layout Field $lAtt->[0]_$_",
                                         $lValue->[0],
                                         $lValue->[1]);
            }

            # the extended attributes
            foreach $lValue (@{$lAtt->[3]})
            {

               $oConfigFileTmp->setValue("Layout Field $lAtt->[0]_$_",
                                      $lValue->[0],
                                      $lValue->[1]);
            }

            &SetField("$lAtt->[0]_$_", $lAtt->[2]);
         }

         $iCnt ++;
      }
   }
   else
   {

   }

   # the extra-fields (not in the database) are added here
   push @lExtraFields, (split ", ",
                        ($oConfigFile->getValue("Data",
                                                "ExtraFields", "")));
   push @lExtraFields, "New_Field";

   # append field-names
   foreach (@lExtraFields)
   {
      my $cBackground = $iCnt % 2? "#eeeeee": "#ffffff";
      my $bInUpdate   = 1;
      my $bInQuery    = 1;
      my $bInIndex    = !$iCnt;
      my @lWork;
      my $cWork;
      my $cType;
      my $cLabel;
      my $cSize;

      push @lFields, $_;

      # Create a nicer label
      $cLabel = "$_:";
      $cLabel =~ s/[-_]/ /g;

      $cLabel = $oConfigFile->getValue("Layout Label $_",
                                       "Text",
                                       $cLabel);

      $cType  = $oConfigFile->getValue("Layout Field $_",
                                       "Type",
                                       "");

      # Get the correct Size-Info
      $cSize = undef;

      if($cType eq "Text")
      {
         $cSize  = $oConfigFile->getValue("Layout Field $_",
                                          "Size",
                                          "40");

      }
      elsif($cType eq "Area")
      {
         $cSize  = sprintf("%dx%d",
                           $oConfigFile->getValue("Layout Field $_",
                                                  "Size",
                                                  "40"),
                           $oConfigFile->getValue("Layout Field $_",
                                                  "Rows",
                                                  "3"));
      }

      if($_ eq "New_Field")
      {
         $oConfigFileTmp->CreateSectionAndEntries
             (["Layout Field Label_New_Field",
               [["Pos"       => "+1.+0.0"],
                ["Type"      => "Text"],
                ["Size"      => "15"],
                ["MustMatch" => q/^\w+$/],
                ["Mandatory" => 1],
                ["BgColor" => $cBackground]]]);
      }
      else
      {
         $oConfigFileTmp->CreateSectionAndEntries
             (["Layout Label $_",
               [["Pos"     => "+1.+0.0"],
                ["Text"    => "$_:   "],
                ["Align"   => "Right"],
                ["Bold"    => "Yes"],
                ["BgColor" => $cBackground]]]);
      }


      # the attributes for each field
      foreach $lAtt ((($_ ne "New_Field")?
                      ["TXT", "Text",        $cLabel,
                       [["Size"      => "20"]]]:
                      ["_TXT", "Label", "&nbsp;"]),
                     (($_ ne "New_Field")?
                      ["TYP", "Select",      $cType,
                       [["Values"    =>
                         (join "\n", ("Text\\," . i18n("Text"),
                                      "Area\\," . i18n("Area"),
                                      "Label\\," . i18n("Label"),
                                      "Hidden\\," . i18n("Hidden"),
                                      "\\," . i18n("Label-Only"),
                                      "Password\\," . i18n("Other"),
                                      "Btn\\," . i18n("Other"),
                                      "Ref\\," . i18n("Other"),
                                      "Checkbutton\\," . i18n("Other"),
                                      "Select\\," . i18n("Other"),
                                      "Radio\\," . i18n("Other")))]]]:
                      ["_TYP", "Label", "&nbsp;"]),
                     (($_ ne "New_Field")?
                      ["SIZ", "Text",        $cSize,
                       [["MustMatch" => q/((\d+)(x(\d+))?)?/],
                        ["Size"      => "6"]]]:
                      ["_SIZ", "Label", "&nbsp;"]),
                     ["WRK", "Btn", "",
                      [["Label"      => ($_ eq "New_Field"?
                                         "Insert.png":
                                         "Delete.png")]]],
                     ($_ ne "New_Field")?
                     ["XTR", "Label", "&nbsp;"]:
                     ["_XTR", "Label", "&nbsp;"],
                     ($_ ne "New_Field")?
                     ["XXX", "Label", "&nbsp;"]:
                     ["_XXX", "Label", "&nbsp;"])
      {

         # the single attributes
         foreach $lValue (["Text",    ""],
                          ["Pos",     "+0.+1.0"],
                          ["Type",    "$lAtt->[1]"],
                          ["Align",   "Center"],
                          ["BgColor", $cBackground])
         {

            $oConfigFileTmp->setValue("Layout Field $lAtt->[0]_$_",
                                      $lValue->[0],
                                      $lValue->[1]);
         }

         # the extended attributes
         foreach $lValue (@{$lAtt->[3]})
         {

            $oConfigFileTmp->setValue("Layout Field $lAtt->[0]_$_",
                                   $lValue->[0],
                                   &DecodeHtml($lValue->[1]));
         }

         &SetField("$lAtt->[0]_$_", &DecodeHtml($lAtt->[2]));
      }

      $iCnt ++;
   }

   &SetField("Label_New_Field", i18n("New_Field"));
   &SetField("Fields", join ",", @lFields);

   # Create some other fields
   $oConfigFileTmp->CreateSectionAndEntries
    (["Layout Label Data_Order",
      [["Text"   => i18n("Default field to use for sorting")],
       ["Pos"    => "+2.0+1.0"]]],
     ["Layout Field Data_Order",
      [["Pos"    => "+0.+1+2.0"],
       ["Type"   => "Select"],
       ["Size"   => "1"],
       ["Values" => (join "\n", (@{$oStmtHdl->{NAME}}))]]],

     ["Layout Label Browser_MaxRows",
      [["Text"   => i18n("Number of rows to display at one page in query-mode")], #
       ["Pos"    => "+1.0+1.0"]]],
     ["Layout Field Browser_MaxRows",
      [["Pos"    => "+0.+1+2.0"],
       ["Type"   => "Select"],
       ["Size"   => "1"],
       ["Values" => (join "\n", (1 .. 20,
                                 25, 30, 35, 40, 50,
                                 100, 200, 300, 400,
                                 9999))]]])
        if($cTable ne "UserFormat");

   $oConfigFileTmp->CreateSectionAndEntries
     (["Layout Label Header_Title",
      [["Text"   => i18n("Header")],
       ["Pos"    => "+1.0+1.0"]]],
     ["Layout Field Header_Title",
      [["Pos"    => "+0.+1+4.0"],
       ["Size"   => "40"],
       ["Values" => (&GetField("DbTable"))]]]);

   &SetField("Data_Order",
             $oConfigFile->getValue("Data", "Order", $lFields[0]));
   &SetField("Browser_MaxRows",
             $oConfigFile->getValue("Browser", "MaxRows", "15"));
   &SetField("Header_Title",
             $oConfigFile->getValue("Header",
                                    "Title",
                                    &GetField("DbTable")));

   undef $oStmtHdl;

   # $oConfigFileTmp->Dump();
   $oConfigFileTmp->WriteFile_Ini();

   $oConfPoolGL->addConfigFile ($oConfigFileTmp);

}

sub MyBtnFinish ()
{
   if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {

      GenConfigFile();

      &Redirect(&GetAttr("SessionId"), "WWWdb:tmp:" . GetField("DbTable"));
   }
}


sub MyBtnNext ()
{

   if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {
      GenConfigFile();

      print &Redirect(&GetAttr("SessionId"), "WWWdb:Wiz:CreateAppRc_2a");
   }
}


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


sub GenConfigFile ()
{
   my @lUpdFields = ();
   my @lQryFields = ();
   my @lXtrFields = ();
   my @lIdxFields = ();
   my @lAllFields = ();
   my $oConfigFile;

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

   # Add this dummy-fields for UserFormat
   if(&GetField("DbTable") eq "UserFormat")
   {
      # push @lUpdFields, "";
      # push @lQryFields, "";
      push @lIdxFields, "-";
   }

   foreach (split ",", &GetField("Fields"))
   {
      next
          if $_ eq "New_Field";

      push @lUpdFields, $_
          if &GetField("UPD_$_");

      push @lQryFields, $_
          if &GetField("QRY_$_");

      push @lXtrFields, $_
          if &GetField("XTR_$_");

      push @lIdxFields, $_
             if &GetField("IDX_$_");
   }


   foreach (["Data",               "Table",       &GetField("DbTable")],
            ["Data",               "Order",
             &GetField("Data_Order")],
            ["Data",               "UpdFields",   join ", ", @lUpdFields],
            ["Data",               "QryFields",   join ", ", @lQryFields],
            ["Data",               "ExtraFields", join ", ", @lXtrFields],
            ["Data",               "IdField",     join ", ", @lIdxFields],
            ["Browser",            "MaxRows",
             &GetField("Browser_MaxRows")],
            ["Qry",                "SelType",     "Link"],
            ["Header",             "Title",
             &GetField("Header_Title")],
            ["State All",          "Dummy",       undef],
            ["State Init",         "Dummy",       undef],
            ["State Work",         "Dummy",       undef],
            ["State Qry",          "Dummy",       undef],
            ["Layout Table",       "Dummy",       undef],
            ["Layout Qry _link",   "Text",        undef],
            ["Layout Qry _link",   "Type",        "Ref"],
            ["Layout Qry _link",   "Value",       "<  >"],
            ["Layout Qry _link",   "Align",       "Right"]
            )
   {
      $oConfigFile->setValue($_->[0], $_->[1], $_->[2]);
   }

   push @lAllFields, @lUpdFields;
   push @lAllFields, @lXtrFields;

   foreach (@lAllFields)
   {
      my $iLines = undef;
      my $cType  = "Text";
      my $iSize  = undef;
      my $cLabelPos;
      my $cFieldPos;


      # checks the following types:
      # <WITTH>
      # <WITTH>x<HEIGHT>
      if (&GetField("SIZ_$_") =~ /(\d+)(x(\d+))?/)
      {
         $iSize = $1
             if $1;
         $iLines = $3
             if $3;

      }

      $cLabelPos =  $oConfigFile->getValue("Layout Label $_",
                                           "Pos",
                                           "+1.0.0");

      $cFieldPos =  $oConfigFile->getValue("Layout Field $_",
                                           "Pos",
                                           "+0.+1.0");

      $oConfigFile->CreateSectionAndEntries
          (["Layout Label $_",
            [["Text"   => &GetField("TXT_$_")],
             ["Pos"    => $cLabelPos]]],
           &GetField("TYP_$_")?
           ["Layout Field $_",
            [["Pos"    => $cFieldPos],
             ["Type"   => &GetField("TYP_$_")],
             ["Size"   => $iSize? $iSize: undef],
             ["Rows"   => $iLines? $iLines: undef]]]:
           undef);

   }

   $oConfigFile->WriteFile_Ini();


   system("cd " . &GetAttr("BaseDir") . "/lib/WWWdb/tmp; " .
          "mv " . &GetField("DbTable") . ".rc.new " . &GetField("DbTable") . ".rc");

}



sub MyBtnWRK_New_Field
{
   my $bFieldIsDuplicate = 0;
   my $cNewFieldName     = &GetField("Label_New_Field");

   if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {
      # Check, if this field is already inserted
      foreach (split ",", &GetField("Fields"))
      {
         $bFieldIsDuplicate = 1
             if $_ eq $cNewFieldName;
      }

      unless ($bFieldIsDuplicate)
      {
         &SetField("Fields", &GetField("Fields") . "," . $cNewFieldName);
         &SetField("XTR_" . &GetField("Label_New_Field"), "1");

         &GenConfigFile();
      }
   }
}



# this is for the deletion of an extra-Field
sub MyBtnWRK_($)
{
   my $cFieldToDeletePI = shift;
   my $oConfigFile;

   if(!&GetAttr("RecordOk"))
   {
      &GenPage();
   }
   else
   {

      &SetField("XTR_" . $cFieldToDeletePI, "");

      # Remove the field from ExtraFields
      &GenConfigFile();

      # Remove the corresponding sections
      $oConfigFile = ConfigFile->new
          (&GetAttr("BaseDir") . "/lib/WWWdb/tmp/" . GetField("DbTable") . ".rc",
           ReadOnly => 0);

      $oConfigFile->deleteSection("Layout Label $cFieldToDeletePI");
      $oConfigFile->deleteSection("Layout Field $cFieldToDeletePI");
      $oConfigFile->deleteSection("Layout Qry $cFieldToDeletePI");
      $oConfigFile->Dump();

      $oConfigFile->WriteFile_Ini();

      system("cd " . &GetAttr("BaseDir") . "/lib/WWWdb/tmp; " .
             "mv " . &GetField("DbTable") . ".rc.new " .
             &GetField("DbTable") . ".rc");

   }

}


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 Check_AppRc()
{
   if(&GetField("Label_New_Field") !~ /^\w+$/)
   {
      &AddError("Label_New_Field",
                sprintf(i18n("Only alphanumeric characters (and _) allowed!"),
                        "Label_New_Field"))
       }
}


1;
