use strict;

use IO::File;
use POSIX qw(tmpnam);

use constant MAX_RECORDS_TO_DOWNLOAD => 5000;
use constant CSV2PD_BCOMMAND         => "/usr/local/bin/csv2pdb";


sub BtnDownloadPdb()
{
   &OkForm("",
           i18n('<br><br>You are now downloading the content of the ' .
                'selected data in the <b>DB</b>-format.' .
                '<br>This is a <i>free</i> database for the Palm-PDAs.' .
                '<p>You will find it at ' .
                '<a href="http://sourceforge.net/projects/pilot-db">' .
                'http://sourceforge.net/projects/pilot-db.</a>' .
                '<p>Download the data, pressing the OK-button. ' .
                'After downloading the file, use the Back-button ' .
                'of the browser.<br><br>').
           sprintf(i18n('Please note, the download is actually ' .
                        ' limited to a maximum of %d records.<br><br>'),
                   MAX_RECORDS_TO_DOWNLOAD),
           "BtnDb2Pdb");
}


sub BtnDb2Pdb()
{
   my $cBuff;
   my $cCsv2PdbCommand = CSV2PD_BCOMMAND . " ";
   my $cField;
   my $cFileCsvName;
   my $cFilePdbName;
   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', MAX_RECORDS_TO_DOWNLOAD);
   &MyParam('$valuesplit', ",");
   &MyParam('$compconj',   "and");

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

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

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

   # makes /tmp/<xxxxx>
   $cFileCsvName = tmpnam() . ".csv";
   $cFilePdbName = tmpnam() . ".pdb";

   foreach $cName (split /, */,
                   &MyVal('Data', 'QryFields'))
   {
      $cCsv2PdbCommand .= "-f $cName,string,80 ";
   }

   $cCsv2PdbCommand .= ("-t '" . &MyVal('Header', 'Title') . "' " .
                        &GetAttr("BaseDir") . $cFileCsvName . " " .
                        &GetAttr("BaseDir") . $cFilePdbName);

   $cCsv2PdbCommand .= (" 2>&1");




   open CSV_FILE, ">" . &GetAttr("BaseDir") . $cFileCsvName
       or die sprintf(i18n("Can't open CSV-File %s!"),
                      $cFileCsvName);

   $iInd = 0;

   while ($pRecord = $pDataSetMGL[$iInd])
   {
      $iInd ++;

       my $iRow = 0;

       foreach $cName (split /, */,
                       &MyVal('Data', 'QryFields'))
       {
           # we need this field for generating a selector for the record

	   {
              my $cValue;

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

              printf CSV_FILE ($iRow? ",": "") . '"' . $cValue. '"';

	   }


	   $iRow ++;
       }

      print CSV_FILE "\n";
   } # while ($pRecord = $pDataSetMGL[$iInd++])

   close CSV_FILE;

   print STDERR "Command: $cCsv2PdbCommand\n";
   $cResult = `$cCsv2PdbCommand`;

   &Error(i18n("During the conversion the following Problem(s) appeared:") .
          br() x 2 .
          $cResult)
       if $cResult;

   open PDB_FILE, "<" . &GetAttr("BaseDir") . $cFilePdbName
       or die sprintf(i18n("Can't open Pdb-File %s!"),
                      $cFilePdbName);

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

   while(read(PDB_FILE, $cBuff, 8192))
   {
      print STDOUT $cBuff;
   }

   close PDB_FILE;

   unlink(&GetAttr("BaseDir") . $cFilePdbName);
   unlink(&GetAttr("BaseDir") . $cFileCsvName);

   # quit here explicitly
   exit;

} # sub QryData

1;
