use strict;

use PDF::Create;

use constant PAGE_X => 612;     # in units
use constant PAGE_Y => 792;     # in units

use constant LEFT_BORDER => 10; # in units
use constant TOP_BORDER  =>  5; # in units

use constant HEADER_SIZE => 60; # in units
use constant FOOTER_SIZE => 30; # in units

use constant RECORD_SIZE => 45; # in units
use constant FIELD_SIZE  => 100; # in units

use constant ROTATE      => 90;

my @lRecWidths = (100,100,100,100,100,100,100,100,100,100,100,100,100);


my $iActualYPosGL = 0;
my $iActualXPosGL = 0;
my $iPageGL       = 0;

sub BtnReport()
{
   my $cBuff;
   my $cField;
   my $cFileCsvName;
   my $cKey;
   my $cName;
   my $cOp;
   my $cRecIdFields;
   my $cResult;
   my $cValue;
   my $iInd;
   my $pRecord;

   $cRecIdFields      = &GetAttr("RecIdField");

   # add id-field to the query
   &MyParam("!Fields",
            ((&MyVal('Qry', 'Distinct')? "DISTINCT ":  "") .
             &MyVal('Data', 'QryFields') .
             ", ".
             $cRecIdFields ));

   &InitDBIxRecordset();

   # Here the User can manipulate form-data
   Plugin->new("PreCreateForm")->Call();

   # create recordset
   *pDataSetMGL = DBIx::Recordset->Setup(\%hFormDataMGL);

   # Get the type-info for the fields
   &GetAllFieldInfo(&MyVal('Data', 'Table'), $pDataSetMGL);

   # construct selection-criteria
   foreach $cKey (keys %hFormDataMGL)
   {

      if ($cKey =~ "^Fld.*" and &MyParam($cKey) ne "")
      {

         # get the fieldname
         ($cField = $cKey) =~ s/^Fld//;

         # we got an operator
         if(&MyParam("\*$cField"))
         {
            &MyParam($cKey,
                     &MyParam("\*$cField") . " " .
                     &MyParam("$cField"));

         }

         # now scan the search-operator
         if(&MyParam($cKey) =~ /^(>=|<=|<|>|!=|=|like)\s*(.*)$/)
         {
            ($cOp, $cValue) = ($1, $2);
         }
         else # no search-operator
         {
            # * is replaced with LIKE
            if (&MyParam($cKey) =~ /\*/)
            {
               ($cValue = &MyParam($cKey)) =~ s/\*/%/g;
               $cOp     = "like";

            }
            else
            {
               $cOp    = "=";
               $cValue = &MyParam($cKey);
            }
         }

         # make this field ready for querying the database
         &MyParam($cKey, $cValue);

         &ConvertDataForDb("Form2Db", $cField);
         $cValue = &MyParam($cKey);

         if($cValue)
         {
             &MyParam("\*$cField", $cOp);
             &MyParam("$cField", $cValue);

             printf STDERR sprintf(i18n("%s => Op: s(%s) Value: s(%s)") .
                                      "<BR>\n",
                                      $cField,
                                      $cOp,
                                      $cValue)
                 if &GetAttr("DebugLvl") > 3;
         }
      } # if ($cKey =~ "Fld.*" and &MyParam($cKey) ne "")
   } # foreach $cKey (keys %hFormDataMGL)

   &InitDBIxRecordset();

   &MyParam('$max', 100000);
   &MyParam('$valuesplit', ",");
   &MyParam('$compconj',   "and");

   &MyParam('$start', "0");

   # Search for Data
   $pDataSetMGL->Search(\%hFormDataMGL);

   # catch DB-error
   &DbiErrorAndExit(i18n("data-querying"));

   print CGI::header(-type       => 'application/pdf',
                     -attachment => &MyVal('Data', 'Table') . ".pdf",
                     -expires    => '+3d');

   my $oPDF = new PDF::Create('fh'       => *STDOUT,
                              'Author'   => 'WWWdb',
                              'PageMode' => 'UseOutlines',
                              'Title'    => &MyVal('Header', 'Title'),
                              'Rotate'    => ROTATE
                              );

   my $oRoot = $oPDF->new_page('MediaBox'  => [ 0, 0, PAGE_X, PAGE_Y ]);

   # Add a page which inherits its attributes from $oRoot
   my $oPage = $oRoot->new_page;

   # Prepare 2 fonts
   my $oTextFont = $oPDF->font('Subtype'  => 'Type1',
                               'Encoding' => 'WinAnsiEncoding',
                               'BaseFont' => 'Helvetica');

   &GenHeader($oPDF, $oPage);
   $iInd = 0;

   while ($pRecord = $pDataSetMGL[$iInd])
   {
      my $iCol = 0;
      my $iLine;
      my $iMaxYOffset = 0;

      $iActualYPosGL += RECORD_SIZE;

      # generate the data-fields
      foreach $cName (split /, */,
                       &MyVal('Data', 'QryFields'))
      {

         my $cValue;
         my ($iYPos, $iXPos) = split(",",
                                     &MyVal("Layout PDF $cName", 'Pos',
                                            sprintf("%d,%d",
                                                    ($iCol * FIELD_SIZE),
                                                    0)));
         $iMaxYOffset = $iYPos
             if ($iMaxYOffset < $iYPos);

         $cValue = $$pRecord{$cName};

         # unmask all " to '
#         $cValue =~ s/\"/\'/g;

         # unmask all \r to ' '
#         $cValue =~ s/\r//g;
#         $cValue =~ s/\n/ /g;

         # compress spaces
#         $cValue =~ s/\s+/ /g;

         &GenText($oPage,
                  $oTextFont,
                  10,
                  $iXPos,
                  $iActualYPosGL + $iYPos,
                  $cValue);


         $iCol ++;

      }

      # draw a line at the end of each record
      $oPage->line(LEFT_BORDER,                         # to x
                  &PDF_LineCoord($iActualYPosGL + $iMaxYOffset + 2),  # to y
                  PAGE_X,                       # from x
                  &PDF_LineCoord($iActualYPosGL + $iMaxYOffset + 2), # from y
                  );
      $iActualYPosGL += 3;

      if(($iActualYPosGL + FOOTER_SIZE + RECORD_SIZE) >= PAGE_Y)
      {
         # Add a page which inherits its attributes from $oRoot
         $oPage = $oRoot->new_page;
         &GenHeader($oPDF, $oPage);

      }

      $iInd ++;

   } # while ($pRecord = $pDataSetMGL[$iInd++])
   # quit here explicitly

   # Add the missing PDF objects and a the footer then close the file
   $oPDF->close;

   close STDOUT;                # FIXME: Dangerous
   exit;

} # sub QryData

sub GenText($$$$$$;$)
{
   my $pPagePI     = shift;
   my $pFontPI     = shift;
   my $iFontSizePI = shift;
   my $iXPosPI     = shift;
   my $iYPosPI     = shift;
   my $cTextPI     = shift;
   # optional
   my $iSizePI     = shift;

   $pPagePI->string($pFontPI,
                    $iFontSizePI,
                    LEFT_BORDER + $iXPosPI,
                    &PDF_LineCoord($iYPosPI),
                    $cTextPI);

   return $cTextPI;
}

sub PDF_LineCoord($)
{
   my $iPos_PI = shift;

   return (PAGE_Y - $iPos_PI);

}

sub GenHeader()
{
   my $pPdf_PI  = shift;
   my $pPage_PI = shift;

   my $oHeaderFont = $pPdf_PI->font('Subtype'  => 'Type1',
                           'Encoding' => 'WinAnsiEncoding',
                           'BaseFont' => 'Helvetica-Bold');

   $iPageGL ++;

   # Header
   {
      my $cName;
      my $iCol = 0;

      $pPage_PI->stringc($oHeaderFont, 16,
                         LEFT_BORDER + (PAGE_X / 2), # column
                         &PDF_LineCoord(TOP_BORDER + (HEADER_SIZE / 4)), # line
                         &MyVal('Header', 'Title'));

      foreach $cName (split /, */,
                      &MyVal('Data', 'QryFields'))
      {
         my $cFieldLabel = &MyVal("Layout PDF $cName", 'Label', $cName);
         my ($iYPos, $iXPos) = split(",",
                                     &MyVal("Layout PDF $cName", 'Pos',
                                            sprintf("%d,%d",
                                                    ($iCol * FIELD_SIZE),
                                                    0)));

         $pPage_PI->string($oHeaderFont, 12,
                            LEFT_BORDER + $iXPos, # column
                            &PDF_LineCoord(TOP_BORDER +
                                           HEADER_SIZE / 2 +
                                           $iYPos), # line
                            i18n($cFieldLabel));

         $iCol ++;
      }

      # header-line
      $pPage_PI->line(LEFT_BORDER,                     # from x
                      &PDF_LineCoord(TOP_BORDER + (HEADER_SIZE - 2)),    # from y
                      PAGE_X,                # to x
                      &PDF_LineCoord(TOP_BORDER + (HEADER_SIZE - 2))     # to y
                      );
   }

   # Footer
   {
      # footer-line
      $pPage_PI->line(LEFT_BORDER,                           # from x
                      &PDF_LineCoord(PAGE_Y - FOOTER_SIZE + 2), # from y
                      PAGE_X,                      # to x
                      &PDF_LineCoord(PAGE_Y - FOOTER_SIZE + 2)  # to y
                      );

      # left text
      $pPage_PI->stringl($oHeaderFont, 10,
                         LEFT_BORDER, # column
                         &PDF_LineCoord(PAGE_Y - (FOOTER_SIZE / 2)), # line
                         i18n("Date: ") .
                         ($oDbSessionGL->DateFromDb(scalar(localtime()))));

      # centered text
      $pPage_PI->stringc($oHeaderFont, 10,
                         LEFT_BORDER + ((PAGE_X - LEFT_BORDER) / 2), # column
                         &PDF_LineCoord(PAGE_Y - (FOOTER_SIZE / 2)), # line
                         "");

      # right text
      $pPage_PI->stringr($oHeaderFont, 10,
                         PAGE_X, # column
                         &PDF_LineCoord(PAGE_Y - (FOOTER_SIZE / 2)), # line
                         i18n("Page " . $iPageGL));
   }

   $iActualYPosGL = HEADER_SIZE + TOP_BORDER;
}

1;
