# defined Plugins:
#
# --- Things, to do, before WWWdb does any Action
# PreDoAction()
#
# --- Things to do, before the HTML-form will be generated
# PreCreateForm()
#
# --- Check-Routine for every field of the Table <Table>
# Check_<Table>_EveryField()
#
# --- Check-Routine for field <Field> of the Table <Table>
# Check_<Table>_<Field>()
#
# --- Check-Routine for the Table <Table> after all single-checks
# Check_<Table>()
#
# --- Conversion for fieldtype <FieldType> of db <Db> coming from form
# <Db>_<FieldType>_Form2Db()
#
# --- Conversion for fieldtype <FieldType> of db <Db> coming from db
# <Db>_<FieldType>_Db2Form()
#
# --- Do action for Button <Btn>
# (Pre|Post|My)Btn<Btn>()
#
# --- Set up the navigation-column on the left side
# (Pre|Post|My)FirstColumn()
#
# --- Generate the header of the form
# (Pre|Post|My)FormHeader()
#
# --- Generate the header of the table
# (Pre|Post|My)TableHeader($)
#
# --- Generate the footer of the table
# (Pre|Post|My)TableFooter()
#
# --- Generate the footer of the page
# (Pre|Post|My)FormFooter()

sub PreCreateForm()
{
   my $cLanguages = "";

   &SetField("BaseLang", &GetAttr("BaseLang"));

   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            key_value
         FROM
            wwwdb_lookup
         WHERE
            lang     = ? AND
            key_name = 'lang_select'",
        &GetAttr("BaseLang"));

   # remember only the language (in key_value)
   @lLang = map {$_->[0]} @$plRecord;

   foreach $cLang (@lLang)
   {
      $cLanguages .= li($cLang);
   }

    &SetField("Lang", $cLanguages);

}


sub MyBtnNew()
{
   my @lResult = &GenTranslateTexts();

   &OkForm("",
           i18n("The translation-records in WWWdb were successfully inserted"));

   &MyExit();

}


sub GenTranslateTexts()
{
   my $cBaseLang = &GetAttr("BaseLang");
   my $cField;
   my $cLang;
   my $iCnt      = 0;
   my $iIdDoc;
   my $iIdLookup;
   my $iIdSword;
   my $iIdText;
   my $lResults  = ();
   my $plRecord;
   my %hDoc;
   my %hLookup;
   my %hSWord;
   my %hTxtLang = ();
   my @lLang;
   my @lResults;


   # ensure, that wwwdb_translation with id = 0 is correct
   $oDbSessionGL->SqlDo
       ("UPDATE wwwdb_translation
           SET
             last_change = ?,
             trans_text  = '?'
           WHERE
             id_text     = 0",
        $oDbSessionGL->DateToDb(scalar(localtime)));

   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            key_value
         FROM
            wwwdb_lookup
         WHERE
            lang     = ? AND
            key_name = 'lang_select'",
        $cBaseLang);

   # remember only the language (in key_value)
   @lLang = map {$_->[0]} @$plRecord;

   foreach $cLang (@lLang)
   {
      next
          if $cBaseLang eq $cLang;

      # wwwdb_objects, which have no translation-text assigned
      $plRecord = $oDbSessionGL->SqlSelect
          ("SELECT
                id_object,
                descript,
                descript_txt_id,
                last_change
            FROM
                wwwdb_object
            WHERE
                descript_txt_id = 0");

      foreach (@$plRecord)
      {
         my $iIdObject;
         my $cDescript;
         my $iDescriptTxtId;
         my $iMaxDescriptTxtId;
         my $cLastChange;

         ($iIdObject,
          $cDescript,
          $iDescriptTxtId,
          $cLastChange)  = @$_;

         $iMaxDescriptTxtId =
             $oDbSessionGL->getMaxId("id_text",
                                     "wwwdb_translation");

         # Insert the text for all languages
         foreach $cLang (@lLang)
         {
            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_translation
                    (id_text, lang, trans_text, last_change)
                  VALUES
                    (?, ?, ?, ?)",
                 $iMaxDescriptTxtId,
                 $cLang,
                 $cDescript,
                 (&GetAttr("BaseLang") eq $cLang?
                  $cLastChange:
                  undef));

            $iCnt ++;
         }

         $oDbSessionGL->SqlDo
             ("UPDATE wwwdb_object
               SET
                  descript_txt_id = ?
               WHERE
                  id_object       = ?",
              $iMaxDescriptTxtId,
              $iIdObject);

         push (@lResults,
               sprintf(i18n("wwwdb_object: %d translations inserted."),
                       $iCnt));

      }

      # texts for wwwdb_category
      foreach $cField ("description", "name", "name_chain")
      {
         # texts for wwwdb_category
         $plRecord = $oDbSessionGL->SqlSelect
             (sprintf("SELECT
                           id_category,
                           %s,
                           %s_txt_id,
                           last_change
                       FROM
                           wwwdb_category
                       WHERE
                           %s_txt_id = 0",
                      $cField,
                      $cField,
                      $cField));

         foreach (@$plRecord)
         {
            my $iIdCategory;
            my $cText;
            my $iTextTxtId;
            my $iMaxTxtId;
            my $cLastChange;

            ($iIdCategory,
             $cText,
             $iTextTxtId,
             $cLastChange)  = @$_;

            $iMaxTxtId =
                $oDbSessionGL->getMaxId("id_text",
                                        "wwwdb_translation");

            # Insert the text for all languages
            foreach $cLang (@lLang)
            {

               $oDbSessionGL->SqlDo
                   ("INSERT INTO wwwdb_translation
                       (id_text, lang, trans_text, last_change)
                     VALUES
                       (?, ?, ?, ?)",
                    $iMaxTxtId,
                    $cLang,
                    $cText,
                    (&GetAttr("BaseLang") eq &GetAttr("Lang")?
                     $cLastChange:
                     undef));

               $iCnt ++;
            }

            $oDbSessionGL->SqlDo
                (sprintf("UPDATE wwwdb_category
                          SET    %s_txt_id   = ?
                          WHERE  id_category = ?",
                         $cField),
                 $iMaxTxtId,
                 $iIdCategory);

         }
      }

      push (@lResults,
            sprintf(i18n("wwwdb_object: %d translations inserted."),
                    $iCnt));
   }

   # copies of wwwdb_doc
   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            id_doc,
            lang
         FROM
            wwwdb_doc
         ORDER BY
            id_doc,
            lang");

   foreach (@$plRecord)
   {
      my $iIdDoc;
      my $cLang;

      ($iIdDoc, $cLang) = @$_;

      $hDoc{$iIdDoc}{$cLang} = 1;

   }

   foreach $iIdDoc (keys %hDoc)
   {

      foreach $cLang (@lLang)
      {
         # next
         #    if $cBaseLang eq $cLang;

         unless (defined $hDoc{$iIdDoc}{$cLang})
         {

            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_doc
                     SELECT
                         id_doc,
                         ?            AS lang,
                         category,
                         sub_category,
                         description,
                         document,
                         sort_nr,
                         NULL         AS last_change
                     FROM wwwdb_doc
                     WHERE
                       id_doc  = ?  AND
                       lang    = ?",
                 $cLang,
                 $iIdDoc,
                 $cBaseLang);

            $iCnt ++;
         }
      }
   }

   # make copies of wwwdb_lookup
   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            id_lookup,
            lang,
            key_name
         FROM
            wwwdb_lookup
         ORDER BY
            id_lookup,
            lang,
            key_name");

   foreach (@$plRecord)
   {
      my $iIdLookup;
      my $cLang;
      my $cKeyName;

      ($iIdLookup, $cLang, $cKeyName) = @$_;

      $hLookup{$iIdLookup}{$cLang} = $cKeyName;

   }

   foreach $iIdLookup (keys %hLookup)
   {

      foreach $cLang (@lLang)
      {
         next
            if $cBaseLang eq $cLang;

         unless (defined $hLookup{$iIdLookup}{$cLang})
         {

            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_lookup
                     SELECT
                         id_lookup,
                         ?            AS lang,
                         key_name,
                         key_value,
                         label,
                         sort_nr,
                         NULL         AS last_change
                     FROM wwwdb_lookup
                     WHERE
                       id_lookup  = ?  AND
                       lang       = ?  AND
                       key_name   = ?",
                 $cLang,
                 $iIdLookup,
                 $cBaseLang,
                 $hLookup{$iIdLookup}{$cBaseLang});

            $iCnt ++;
         }
      }
   }


   # copies of wwwdb_sword
   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            id_sword,
            lang,
            sword
         FROM
            wwwdb_sword
         ORDER BY
            id_sword,
            lang,
            sword");

   foreach (@$plRecord)
   {
      my $iIdSword;
      my $cLang;
      my $cSWord;

      ($iIdSword, $cLang, $cSWord) = @$_;

      $hSWord{$iIdSword}{$cLang} = $cSWord;

   }

   foreach $iIdSword (sort keys %hSWord)
   {

      foreach $cLang (@lLang)
      {
         next
             unless $cLang;

         unless (defined $hSWord{$iIdSword}{$cLang})
         {
            my $cNewSword = "";

            $cNewSword = "$hSWord{$iIdSword}{$cBaseLang}"
                if defined "$hSWord{$iIdSword}{$cBaseLang}";

            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_sword
                     (id_sword, lang, sword, last_change)
                  VALUES
                     (?, ?, ?, ?)",
                 $iIdSword,
                 $cLang,
                 $cNewSword,
                 undef);

            $iCnt ++;
         }
      }
   }

   # All texts, that are not translated to any language
   $plRecord = $oDbSessionGL->SqlSelect
       ("SELECT
            id_text,
            lang,
            trans_text
         FROM
            wwwdb_translation
         ORDER BY
            id_text, last_change DESC");

   # Select all texts and store them in a hash
   foreach (@$plRecord)
   {
      my $iIdText;
      my $cLang;
      my $cTransText;

      ($iIdText, $cLang, $cTransText) = @$_;

      $hTxtLang{$iIdText}{$cLang} = $cTransText;
      $hTxtLang{$iIdText}{"NewestLang"} = $cLang
          unless defined $hTxtLang{$iIdText}{"NewestLang"};

   }


   # Now scan every single text, using its id
   foreach $iIdText (keys %hTxtLang)
   {

      # scan every language
      foreach $cLang (@lLang)
      {
         my $cBaseLang = &GetAttr("BaseLang");

         $cBaseLang = $hTxtLang{$iIdText}{"NewestLang"}
              unless defined $hTxtLang{$iIdText}{$cLang};

         # when this text is already defined in this language,
         # everything is ok now
         unless (defined $hTxtLang{$iIdText}{$cLang})
         {

            # We have to create a new record for this text
            $hTxtLang{$iIdText}{$cLang} =
                $hTxtLang{$iIdText}{$cBaseLang};

            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_translation
                    (id_text, lang, trans_text, last_change)
                  VALUES
                    (?, ?, ?, ?)",
                 $iIdText,
                 $cLang,
                 $hTxtLang{$iIdText}{$cBaseLang},
                 undef);

            $iCnt ++;
         }
      }
   }

   # Find out all unneded translation-texts
   {
      my %hUnusedTxtId = ();

      $plRecord = $oDbSessionGL->SqlSelect
          ("SELECT
                id_text
            FROM
                wwwdb_translation
            WHERE
                id_text > 0");

      # remember all availlable texts
      foreach (@$plRecord)
      {
         $hUsedTxtId{$_->[0]} = $_->[0]
      }


      $plRecord = $oDbSessionGL->SqlSelect
          ("SELECT
                descript_txt_id
            FROM
                wwwdb_object
            WHERE
                descript_txt_id > 0");

      # remove all texts, which are used by wwwdb_object
      foreach (@$plRecord)
      {
         delete $hUsedTxtId{$_->[0]};
      }

      # texts for wwwdb_category
      foreach $cField ("description", "name", "name_chain")
      {
         # texts for wwwdb_category
         $plRecord = $oDbSessionGL->SqlSelect
             (sprintf("SELECT
                           %s_txt_id
                       FROM
                           wwwdb_category
                       WHERE
                           %s_txt_id > 0",
                      $cField,
                      $cField));

         foreach (@$plRecord)
         {
            delete $hUsedTxtId{$_->[0]};
         }
      }

      foreach (sort keys %hUsedTxtId)
      {
         $oDbSessionGL->SqlDo
             ("UPDATE wwwdb_translation
                 SET
                   last_change = ?,
                   id_text     = ?
                 WHERE
                   id_text     = ?",
              $oDbSessionGL->DateToDb(scalar(localtime)),
              "-$_",
              $_);
         printf STDERR "XXXXXXXX: obsolete text: %d\n", $_;
      }

   }

   return @lResults;
}



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

   $cResult .= (br() x 2 .
                b(i18n("Don't forget:")) .
                li(&ResolveRefField("wwwdb://WWWdb:NavCatReorg",
                                    i18n("Category-Reorg."))));
   $cResult .= (br() x 2 .
                b(i18n("See also:")) .
                li(&ResolveRefField("wwwdb://WWWdb:NavCat",
                                    i18n("Edit categories"))) .
                li(&ResolveRefField("wwwdb://WWWdb:NavObj",
                                    i18n("Edit objects"))));

   return small($cResult);
}



1;
