use strict;


# --- Things to do, before the HTML-form will be generated
sub PreCreateForm()
{
   my $plCategories;
   my $plSWords;
   my @lModules = ();
   my $plSelect;
   my $cResult;

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

   # make entering the URL more easy
   if (&GetField("ref_link") =~ m!^(.+)://(.+)$!)
   {
      &SetField("link_type",  $1);
      &SetField("link_value", $2);

      if (&GetField("link_value") =~ m!^(.+);(.+)$!)
      {
         &SetField("link_value", $1);
         &SetField("link_param", $2);
      }
   }

   if (&GetField("id_object") and
       &GetField("id_object") < 10000)
   {
      &SetField("id_system",  1);
   }

   if(&GetField("id_object") &&
      (&GetAttr("RecordOk") || GetAttr("LastBtn") =~ /^BtnSel.*/))
   {

      $plCategories = $oDbSessionGL->SqlSelect
          ("SELECT
                t0.id_category
            FROM
                wwwdb_category t0,
                wwwdb_obj_cat t1,
                wwwdb_object t2
            WHERE
                t0.id_category = t1.id_category AND
                t1.id_object   = t2.id_object   AND
                t1.id_object   = ?",
           &GetField("id_object"));

      # Link the records together
      &SetField("cat", join "\\,", map {$_->[0]} @$plCategories);

      $plSWords = $oDbSessionGL->SqlSelect
          ("SELECT
                t2.sword
            FROM
                wwwdb_object t0,
                wwwdb_obj_swd t1,
                wwwdb_sword t2
            WHERE
                t0.id_object = t1.id_object AND
                t1.id_sword  = t2.id_sword  AND
                t2.lang      = ?            AND
                t1.id_object = ?",
           &GetAttr("BaseLang"),
           &GetField("id_object"));

      # Link the records together
      &SetField("swords", join " ", sort map {$_->[0]} @$plSWords);

      # reset the errors
      &GetAttr("RecordOk");
   }

   $plSelect = $oDbSessionGL->SqlSelect
       ("SELECT DISTINCT
             key_value, label
         FROM
             wwwdb_lookup
         WHERE
             lang      = ?         AND
             (key_name = 'AdmAtt' OR
              key_name = 'UserAtt')
         ORDER BY
              key_value",
        &GetAttr("Lang"));

   &MySetVal("Layout Field poss_attribs", "Values",
             join "\n", map
             {
                $_->[0] . "\\," . $_->[1] . " (" . $_->[0] . ")";
             } @$plSelect);

   $cResult = &GetSortNrList();

   &MySetVal("Layout Field sort_nr", "Type", "Select");
   &MySetVal("Layout Field sort_nr", "Values", $cResult);

}


# --- Check-Routine for the Table after all single-checks
sub Check_wwwdb_object()
{

   foreach ("cat", "swords")
   {
      &InternalFieldCheck($_);
   }

   # Set time-stamp
   &SetField("last_change",
             $oDbSessionGL->DateToDb(scalar(localtime())));

   &SetField("ref_link",
             (&GetField("link_type") .
              "://" .
              &GetField("link_value").
              (&GetField("link_param")?
               ";" . &GetField("link_param"):
               "")));

}



sub PreBtnNew()
{
   my $iMaxObjId;

   # generate a new object-id
   $iMaxObjId = $oDbSessionGL->SqlSelect
       (sprintf("SELECT MAX(id_object)
                 FROM   wwwdb_object
                 WHERE  %s",
                &GetField("id_system")?
                "id_object < 10000":
                "id_object >= 10000"))->[0]->[0];

   &SetField("id_object", ($iMaxObjId?
                           $iMaxObjId + 1:
                           (&GetField("id_system")?
                            1 : 10000)));

   # not translated
   &SetField("descript_txt_id", 0);

}



sub PreBtnQry()
{
   &SetField("ref_link",
             ((&GetField("link_type")?
               &GetField("link_param") . "://":
               "") .
              &GetField("link_value").
              (&GetField("link_param")?
               ";" . &GetField("link_param"):
               "")));
}

sub PostBtnNew()
{
   if (&GetAttr("RecordOk"))
   {
      &UpdateObjRelations("New");

      print &Redirect(&GetAttr("SessionId"),
                      sprintf("WWWdb:NavObj;id=%s",
                              &GetField("id_object")));

   }
}


sub PostBtnUpd()
{

   &UpdateObjRelations("Upd")
       if &GetAttr("RecordOk");

}


sub PostBtnDel()
{

   &UpdateObjRelations("Del");

}



sub UpdateObjRelations($)
{
   my $cUpdTypePI = shift;

   my $iIdObject = &GetField("id_object");

#   assert ($iIdObject)
#       if DEVELOP_VERSION == 1;

   # Delete all links of this object to category and sword
   if($cUpdTypePI eq "Upd" or $cUpdTypePI eq "Del")
   {
      $oDbSessionGL->SqlDo
          ("DELETE FROM wwwdb_obj_cat
            WHERE id_object = ?",
           $iIdObject);

      $oDbSessionGL->SqlDo
          ("DELETE FROM wwwdb_obj_swd
            WHERE id_object = ?",
           $iIdObject);
   }

   # Force the translations
   if($cUpdTypePI eq "Upd")
   {
      if(&GetField("descript_txt_id") > 0)
      {
         # mark all texts, so they have to be translated
         $oDbSessionGL->SqlDo
             ("UPDATE wwwdb_translation
                 SET last_change = NULL
                 WHERE id_text = ?",
              &GetField("descript_txt_id"));

         # make a base-language translation-record
         $oDbSessionGL->SqlDo
             ("DELETE FROM wwwdb_translation
               WHERE
                   id_text = ? AND
                   lang    = ?",
              &GetField("descript_txt_id"),
              &GetAttr("BaseLang"));

         $oDbSessionGL->SqlDo
             ("INSERT INTO wwwdb_translation
                 (id_text, lang, trans_text, last_change)
               VALUES
                 (?, ?, ?, ?)",
              &GetField("descript_txt_id"),
              &GetAttr("BaseLang"),
              &GetField("descript"),
              $oDbSessionGL->DateToDb(scalar(localtime)));

      }
   }

   # Delete the translations
   if($cUpdTypePI eq "Del")
   {
      # until this text is translated, the original text will be used
      $oDbSessionGL->SqlDo
          ("DELETE FROM wwwdb_translation
            WHERE id_text = ?",
           &GetField("descript_txt_id"))
              if &GetField("descript_txt_id") > 0;
   }

   if($cUpdTypePI eq "Upd" or $cUpdTypePI eq "New")
   {
      my $iIdCat;
      my $cSword;

      # Connect object to categories
      foreach $iIdCat (split /\\,/, &GetField("cat"))
      {
         $oDbSessionGL->SqlDo
             ("INSERT INTO wwwdb_obj_cat
                  (id_object, id_category, last_change)
               VALUES
                  (?, ?, ?)",
              $iIdObject,
              $iIdCat,
              $oDbSessionGL->DateToDb(scalar(localtime)));
      }

      # now handle every sword
      foreach $cSword (split " ", &GetField("swords"))
      {
         my $iIdSword;
         my $iMaxIdSword;

         $iIdSword = $oDbSessionGL->SqlSelect
             ("SELECT id_sword
               FROM wwwdb_sword
               WHERE
                   sword = ?   AND
                   lang  = ?",
              lc($cSword),
              &GetAttr("BaseLang"))->[0]->[0];

         # if this sword does not exist, insert it
         unless ($iIdSword)
         {
            $iMaxIdSword = $oDbSessionGL->getMaxId("id_sword",
                                                   "wwwdb_sword");

            $oDbSessionGL->SqlDo
                ("INSERT INTO wwwdb_sword
                    (id_sword, lang, sword, last_change)
                  VALUES
                    (?, ?, ?, ?)",
                 $iMaxIdSword,
                 &GetAttr("BaseLang"),
                 lc($cSword),
                 $oDbSessionGL->DateToDb(scalar(localtime)));

            $iIdSword = $iMaxIdSword;
         }

         $oDbSessionGL->SqlDo
             ("INSERT INTO wwwdb_obj_swd
                 (id_object, id_sword, last_change)
               VALUES
                 (?, ?, ?)",
              $iIdObject,
              $iIdSword,
              $oDbSessionGL->DateToDb(scalar(localtime)));
      }
   }
}


sub BtnCat ()
{
   print &Redirect(&GetAttr("SessionId"), "WWWdb:NavCat");
}


sub BtnCopyAttribs ()
{
   my $cPossAttribs = &GetField("poss_attribs");

   $cPossAttribs =~ s/\\,/ && /g;
   &SetField("attribs", $cPossAttribs);

   if (&GetField("id_object"))
   {
      &MyParam("WWWdbState", "Work");
   }
   else
   {
      &MyParam("WWWdbState", "Init");
   }

   &GenPage();

}



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

   $cResult .= (br() x 2 .
                b(i18n("Don't forget:")) .
                li(&ResolveRefField("wwwdb://WWWdb:System:TransGenRecords",
                                    i18n("Transl.-Generation"))) .
                li(&ResolveRefField("wwwdb://WWWdb:NavCatReorg",
                                    i18n("Reorganisation"))));

   $cResult .= (br() x 2 .
                b(i18n("See also:")) .
                li(&ResolveRefField("wwwdb://WWWdb:NavCat",
                                    i18n("Edit categories"))));

   return small($cResult);

}


sub GetSortNrList($)
{
   my %hSortNr  = ();
   my $cResult = "";
   my $plSelect;

   $plSelect = $oDbSessionGL->SqlSelect
         ("SELECT
               t4.id_object,
               t4.descript,
               t4.sort_nr,
               t5.trans_text
           FROM
               wwwdb_obj_cat     t3,
               wwwdb_object      t4,
               wwwdb_translation t5
           WHERE
               (t3.id_category  = ?)                  AND
               (t3.id_object    = t4.id_object)       AND
               (t5.id_text      = t4.descript_txt_id) AND
               (t5.lang         = ?)
           ORDER BY
               t4.sort_nr asc",
          &GetField("cat"),
          &GetAttr("Lang"));

   {
      my $iLastSortNr = 0;

      foreach (@$plSelect)
      {
         if($_->[2] eq "" || $_->[2] == 0 || defined $hSortNr{$_->[2]})
         {
            # currently do nothing
         }
         else
         {
            $hSortNr{$_->[2]} = (sprintf("%05d: ", $_->[2]) .
                                 ($_->[3] eq "?"?
                                  $_->[1]:
                                  $_->[3]));
         }
      }

      foreach (sort {$a <=> $b}
               keys %hSortNr)
      {
         my $iNewKey = int(($iLastSortNr + $_) / 2);

         $iLastSortNr = $_;

         $cResult .= sprintf ("%s\\,%s\n" x 2,
                              $iNewKey,
                              sprintf("%05d: ...", $iNewKey),
                              $_,
                              $hSortNr{$_});
      }

      $cResult .= sprintf ("%s\\,%s\n",
                              ($iLastSortNr + 10),
                              sprintf("%05d: ...", ($iLastSortNr + 10)));

   }

   return $cResult;
}

1;
