use HTML::TreeBuilder;

use strict;

# --- Things to do, before the HTML-form will be generated

use File::Basename;

# --- Things to do, before the HTML-form will be generated
sub PreCreateForm()
{
   my @lCategories;
   my $cTextField = &GetField("document");
   my $cResult;

   &SetField("lang", &GetAttr("Lang"))
       unless (&GetField("lang"));

   if (&GetField("id_doc") and
       &GetField("id_doc") < 1000)
   {
      &SetField("id_system",  1);
   }

   if($cTextField =~ m!^<WWWdb FILE=(.*)/>$!)
   {
      my $cContentOfFile = "";
      my $cFileName;

      $cFileName = (&GetAttr("BaseDir") .
                    "/lib/Data/wwwdb_doc/" .
                    $1);

      open TEXTFILE, "<$cFileName" or
          die sprintf(i18n("Can't open %s"), $cFileName);

      # Read a text file and print it out
      while (<TEXTFILE>)
      {
         $cContentOfFile .= $_;
      }
      close TEXTFILE;

      &SetField("document", $cContentOfFile);
   }

   if (&GetField("id_doc"))
   {
      &ExportFile();

      $cResult = &GetSortNrList();

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

# --- Feld conttyp1 prüfen -----------------------------------------------
sub Check_wwwdb_doc()
{

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


sub PreBtnNew()
{
   my $iMaxObjId;

   # generate a new object-id
   $iMaxObjId = $oDbSessionGL->SqlSelect
       (sprintf("SELECT MAX(id_doc)
                 FROM wwwdb_doc
                 WHERE
                     %s   AND
                     lang = '%s'",
                (&GetField("id_system")?
                 "id_doc < 10000":
                 "id_doc >= 10000"),
                &GetAttr("BaseLang")))->[0]->[0];

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

   &HandleTextFile("Write");

}

sub PostBtnNew ()
{

   print &Redirect(&GetAttr("SessionId"),
                   sprintf("WWWdb:System:Doc;id=%s,%s",
                           &GetField("id_doc"),
                           &GetField("lang")))
       if &GetAttr("RecordOk");

}



sub PreBtnUpd()
{
   &HandleTextFile("Write");
}

sub PostBtnDel()
{
   &HandleTextFile("Del");
}


sub MyBtnImpInit()
{
   &ImportData();
   &MyParam("WWWdbState", "Init");
   &GenPage();
}


sub MyBtnImpWork()
{
   &ImportData();
   &MyParam("WWWdbState", "Work");
   &GenPage();
}


sub ImportData()
{

   # because this is a filehandle we must go this way ...
   my $cFilename      = param("Fldimport_file");
   my $cContentOfFile = "";
   my $oHtmlTree      = HTML::TreeBuilder->new();
   my $oBody;

   if($cFilename)
   {
      my $iSize;
      my $cData;
      my $iTotalSize;

      while ($iSize = read($cFilename, $cData, 1024))
      {
         $cContentOfFile .= $cData;
         $iTotalSize += $iSize;
      }


      # here we parse the HTML-document and extract only the
      # body
      $oHtmlTree->parse($cContentOfFile);
      $oHtmlTree->eof();

      $oBody = $oHtmlTree->look_down('_tag', 'body');

      if($oBody)
      {
         $cContentOfFile = "";

         $cContentOfFile = $oBody->as_HTML(undef, " ");
      }
      $oHtmlTree->delete();

      &SetField("document", $cContentOfFile);
   }

}



sub MyBtnView()
{
   my $cField = &GetField("document");

   $cField = &ScanDoc($cField);

   &OkForm("",
           (b(i18n("Preview of current entry")) .
            br() x 2 .
            table({-BORDER      => 1,
                   -CELLPADDING => 10},
                  TR(td(p({-ALIGN  => "CENTER"},
                          big(b(&GetField("description")))) .
                        hr({-NOSHADE => 1}) .
                        p({-ALIGN  => "LEFT"},
                          $cField)))) .
            br() x 2 .
            i18n("Please use the back-button of your browser")),
           "-");

   &MyExit();
}




sub ExportFile()
{
   my $cExportFileName = &UnTaint(&GenExportFileName());

   open HTML_EXP, ">$cExportFileName"
       or die sprintf(i18n("Can't open %s"),
                      $cExportFileName);

   print HTML_EXP html(body(&GetField("document")));

   close HTML_EXP;

   chmod 0666, $cExportFileName;

   &SetField("export_file", "wwwdb://../../../" .
             &GetAttr("ScriptName") .
             "/tmp/" .
             basename("$cExportFileName"));

   &MySetVal("Layout Field export_file", "Value",
             basename("$cExportFileName"));

   &SetField("show_url",
             sprintf("wwwdb://WWWdb:Tools:ShowDoc;id=%d,%s",
                     &GetField("id_doc"),
                     &GetField("lang")));


}


sub GenExportFileName ()
{
   my $cResult = "";
   my $cBuffer = "";

   foreach ("id_doc", "lang",
            "description")
   {
      $cBuffer .= &GetField($_) . "_";
   }

   $cBuffer =~ s/[^A-Za-z0-9_]//g;
   # $cBuffer =~ s/[aeiouAEIOU]//g;
   $cBuffer =~ s/_$//g;

   $cResult = (&GetAttr("BaseDir") .
               "/tmp/" .
               $cBuffer .
               ".html");

   return $cResult;
}


sub HandleTextFile($)
{
   my $cActionPI = shift;
   my $cText;

   $cText = &GetField("document");

   # write the contents of the textfield to a file, if it exceeds 4k
   if(length($cText) > 1024 * 4)
   {
      my $cFileName;

      $cFileName = (&GetAttr("BaseDir") .
                    "/lib/Data/wwwdb_doc/" .
                    sprintf("%06d_%s.html",
                            &GetField("id_doc"),
                            &GetField("lang")));

      if($cActionPI eq "Write")
      {
         open HTML_EXP, ">$cFileName" or
             die sprintf(i18n("Can't open %s"), $cFileName);

         print HTML_EXP &GetField("document");
         close HTML_EXP;
         chmod 0666, $cFileName;

         &SetField("document", sprintf("<WWWdb FILE=%06d_%s.html/>",
                                   &GetField("id_doc"),
                                   &GetField("lang")));
      }
      elsif($cActionPI eq "Del")
      {
         unlink($cFileName);
      }
   }
}


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


   if(&IsAttribOK("ActualLogin") && &IsAttribOK("IsAdmin") &&
      &GetField("id_doc"))
   {
      $cResult .= (br() x 2 .
                   b(i18n("View:")) .
                   &ResolveRefField("wwwdb://WWWdb:Tools:ShowDoc;id=" .
                                    &GetField("id_doc") .
                                    "," .
                                    &GetField("lang"),
                                    i18n("This document")));
   }

   return small($cResult);

}


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


   printf STDERR ("'%s', '%s', '%s'\n",
                  &GetField("category"),
                  &GetField("sub_category"),
                  &GetAttr("Lang"));

   $oDbSessionGL->setDebugLvl(10);

   # it seems real crazy, but if you comment out this statement,
   # you will get an error after importing. Does anyone know why?????
   $oDbSessionGL->{"DbHandle"}->trace(10);

   $plSelect = $oDbSessionGL->SqlSelect
       ("SELECT
             t0.id_doc,
             t0.description,
             t0.lang,
             t0.sort_nr
         FROM
             wwwdb_doc t0
         WHERE
             t0.category     = ? AND
             t0.sub_category = ? AND
             t0.lang         = ?",
            &GetField("category"),
            &GetField("sub_category"),
            &GetAttr("Lang"));

   {
      my $iLastSortNr = 0;

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

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

sub QryConv_last_change()
{
   return $oDbSessionGL->DateFromDb(shift);

}

1;
