package ticketserver::Qooxdoo;

use JSON qw(to_json);
use strict;
use warnings;
use ADBGUI::BasicVariables;
use ADBGUI::Qooxdoo;
use ADBGUI::Tools qw(Log);
use ticketserver::DBDesign qw($TICKETS $BOXES $VERBUND $CUSTOMER $VORLAGE $PASS $TICKETTIMEOUTDAY $MAC $BUCHUNGEN $ZAHLUNGSART);
use HTTP::Status;
use GD::Barcode::QRcode;
use pdfmaker::Tools qw(showHTMLDocumentAsPDF);
use POE;
our @ISA;

sub new {
   my $proto = shift;
   my $class = ref($proto) || $proto;
   my $self = shift;
   my $parent = $self ? ref($self) : "";
   @ISA = ($parent) if $parent;
   $self = $self ? $self : {};
   bless ($self, $class);
   return $self;
}

sub onShow {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;

   unless ((!$moreparams) && $options->{curSession} && $options->{table} && $options->{connection}) {
      Log("onShow: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.":connection:".$options->{connection}.": !", $ERROR
);
      return undef;
   }
   my $return = $self->SUPER::onShow($options);
   if ($options->{table} eq $TICKETS) {
      my $suffix = "show";
      my $wid = $options->{table}."_".$suffix;
      $poe_kernel->yield(sendToQX => "maximize ".$wid." 1");
   }
   return $return;
}

sub onAuthenticated {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{curSession}) {
      Log("onAuthenticated: Missing parameters: curSession:".$options->{curSession}.": !", $ERROR);
      return undef;
   }
   if (defined(my $err = $self->{dbm}->checkRights($options->{curSession}, $MODIFY))) {
      foreach my $curtable ($TICKETS) {
         $poe_kernel->yield(sendToQX => "addbutton  ".CGI::escape($curtable)." ".CGI::escape($self->{dbm}->getTableDefiniton($curtable)->{label} || $curtable)." ".CGI::escape($self->{dbm}->getTableDefiniton($curtable)->{icon})." ".CGI::escape("job=show,table=".$curtable));
      }
   } else {
      $self->SUPER::onAuthenticated($options);
      #unless ($options->{curSession}->{rights} & $ADMIN) {
      #   $poe_kernel->yield(sendToQX => "addbutton  ".CGI::escape("blabla")." ".CGI::escape("HTML-Dateien")." ".CGI::escape("resource/qx/icon/Tango/32/actions/document-properties.png")." ".CGI::escape("job=neweditentry,table=".$CUSTOMER.",".$UNIQIDCOLUMNNAME."=".$options->{curSession}->{$USERSTABLENAME.$TSEP.$CUSTOMER."_".$UNIQIDCOLUMNNAME}));
      #}
   }
   unless ($options->{curSession}->{rights} & $ADMIN) {
      #$self->onShow({table => $TICKETS, curSession => $options->{curSession}});
      $poe_kernel->yield(sendToQX => "addmenu  neuetickets ".CGI::escape("Neues ".($self->{dbm}->getTableDefiniton($TICKETS)->{label} || $TICKETS))." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")); # CGI::escape($self->{dbm}->getTableDefiniton($TICKETS)->{icon}));
      $poe_kernel->yield(sendToQX => "addbutton neuetickets ".CGI::escape("menu add ticket")." ".CGI::escape("2 Stunden")." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")." ".CGI::escape("job=neweditentry,table=".$TICKETS.",".$TICKETS.$TSEP."mydate=2h"));
      $poe_kernel->yield(sendToQX => "addbutton neuetickets ".CGI::escape("menu add ticket")." ".CGI::escape("1 Tag")." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")." ".CGI::escape("job=neweditentry,table=".$TICKETS.",".$TICKETS.$TSEP."mydate=1d"));
      $poe_kernel->yield(sendToQX => "addbutton neuetickets ".CGI::escape("menu add ticket")." ".CGI::escape("1 Woche")." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")." ".CGI::escape("job=neweditentry,table=".$TICKETS.",".$TICKETS.$TSEP."mydate=1w"));
      $poe_kernel->yield(sendToQX => "addbutton neuetickets ".CGI::escape("menu add ticket")." ".CGI::escape("1 Jahr")." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")." ".CGI::escape("job=neweditentry,table=".$TICKETS.",".$TICKETS.$TSEP."mydate=1y"));
      $poe_kernel->yield(sendToQX => "addbutton neuetickets ".CGI::escape("menu add ticket")." ".CGI::escape("Eigene Eingabe")." ".CGI::escape("resource/qx/icon/Tango/32/list-add.png")." ".CGI::escape("job=neweditentry,table=".$TICKETS.",".$TICKETS.$TSEP."mydate=own"));
   }
   #$poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Debug")." 400 200 ".CGI::escape("Customer ID: ".$options->{curSession}->{$USERSTABLENAME.$TSEP.$CUSTOMER."_".$UNIQIDCOLUMNNAME}));
}

sub getTableButtonsDef {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{table} && $options->{curSession}) {
      Log("getTableButtonsDef: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.": !", $ERROR);
      return undef;
   }
   my $curtabledef = $self->{dbm}->getTableDefiniton($options->{table});
   my $tabledef = $self->SUPER::getTableButtonsDef($options);
   if ($options->{table} eq $TICKETS) {
      my $label = "Ticketausdruck";
      my $icon = "resource/qx/icon/Tango/32/mimetypes/office-document.png";
      my $action = "ticketprint";
      my $row = "row";
      if ($self->{dbm}->{config}->{nojson}) {
         $tabledef->[0] .= ($tabledef->[0] ? "," : "").CGI::escape($label);
         $tabledef->[1] .= ($tabledef->[1] ? "," : "").CGI::escape($icon);
         $tabledef->[2] .= ($tabledef->[2] ? "," : "").CGI::escape($action);
         $tabledef->[3] .= ($tabledef->[3] ? "," : "").CGI::escape($row);
      } else {
         #push(@{$tabledef->[1]}, {
         #   name => $action,
         #   label => $label,
         #   image => $icon,
         #   action => $action,
         #   bindto => $row,
         #});
         push(@{$tabledef->[1]}, {
            name => $action."RAW",
            label => $label,
            image => $icon,
            action => $action."RAW",
            bindto => $row,
         });
      }
   } elsif (($options->{table} eq "mac") ||
            ($options->{table} eq "enduser")) {
      my $row = "row";
      push(@{$tabledef->[1]}, {
         name => "viewmac",
         label => "Ticket",
         image => "bilder/ticket.png",
         action => "viewmac",
         bindto => $row,
      });
   } elsif ($options->{table} eq $TICKETTIMEOUTDAY) {
      my $label = "Aktivieren";
      my $icon = ""; # resource/qx/icon/Tango/32/mimetypes/office-document.png";
      my $action = "ticketcalc";
      my $row = "table";
      if ($self->{dbm}->{config}->{nojson}) {
         $tabledef->[0] .= ($tabledef->[0] ? "," : "").CGI::escape($label);
         $tabledef->[1] .= ($tabledef->[1] ? "," : "").CGI::escape($icon);
         $tabledef->[2] .= ($tabledef->[2] ? "," : "").CGI::escape($action);
         $tabledef->[3] .= ($tabledef->[3] ? "," : "").CGI::escape($row);
      } else {
         push(@{$tabledef->[1]}, {
            name => $action,
            label => $label,
            image => $icon,
            action => $action,
            bindto => $row,
         });
      }
   }
   return $tabledef;
}

sub onClientData {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{heap}) {
      Log("onClientData: Missing parameters: connection:".$options->{heap}.": !", $ERROR);
      return undef;
   }
   if ($options->{job} eq "ticketprint") {
      return $self->ticketprint($options);
   } elsif ($options->{job} eq "ticketcalc") {
      if (my $error = $self->{dbm}->updateTicketEnd($options->{curSession})) {
         $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape($error));
         Log($error, $ERROR);
      }
      return;
   } elsif ($options->{job} eq "ticketprintRAW") {
      return $self->ticketExport($options);
   } elsif ($options->{job} eq "ticketbook") {
      return $self->ticketBook($options);
   } elsif ($options->{job} eq "viewmac") {
      if ($options->{id}) {
         my $db = $self->{dbm}->getDBBackend($options->{table});
         my $ret = undef;
         my $where = $self->{dbm}->Where_Pre($options->{curSession}, $options->{table});
         if (defined($ret = $db->getDataSet({
            session  => $options->{curSession},
            table    => $options->{table},
            id => $options->{id},
            wherePre => $where,
            simple => 1,
         })) && (ref($ret) eq "ARRAY") && (scalar(@{$ret->[0]}))) {
            my $mac = $ret->[0]->[0]->{$options->{table}.$TSEP."address"};
            $poe_kernel->yield(sendToQX => "json ".CGI::escape(JSON->new->allow_nonref->encode({
               job => "openintab",
               url => 'https:///'.$self->{dbm}->{config}->{id}.".login.jetzt/cgi-bin/gui.pl/".$mac,
            })));
         }
      } else {
         my $error = "Keine ID fuer MAC";
         $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape($error));
      }
      return;
   } elsif ($options->{job} eq "ticketinfo") {
      return $self->ticketInfo($options);
   } elsif ($options->{job} eq "qrcode") {
      $options->{response}->code(RC_OK);
      if ($options->{id}) {
         $options->{response}->content_type("image/png");
         my $gd = undef;
         my $id = $options->{id};
         $id =~ s,_,&,g;
         print "XXX:".$id."\n";
         eval {
            $gd = GD::Barcode::QRcode->new($id, { Ecc => 'L', Version=> $options->{moduleversion} || $options->{connection}->{"q"}->param("moduleversion") || 2, ModuleSize => $options->{modulesize} || $options->{connection}->{"q"}->param("modulesize") || 16});
         };
         if ($@) {
            $options->{response}->content_type("text/plain");
            my $error = "Error creating QRCode: ".$@;
            ${$options->{content}} .= $error;
            Log($error, $WARNING);
         } else {
            $options->{response}->content_type("image/png");
            my $height = $options->{moduleheight} || $options->{connection}->{"q"}->param("moduleheight");
            ${$options->{content}} .= $gd->plot((defined $height) ? $height : ())->png;
         }
      } else {
         $options->{response}->content_type("text/html");
         ${$options->{content}} .= "No id given!";
      }
      return;
   }
   return $self->SUPER::onClientData($options);
}

sub ticketBook {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless (!$moreparams) {
      Log("DBManager: ticketprint: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.":id:".$options->{id}."!", $ERROR);
      return 0;
   }
   my $json = {};
   my $brums = $self->{dbm}->getVerifiedNum(uc($options->{connection}->{"q"}->param("code")));
   unless ($brums) {
      my $tmp = $options->{connection}->{"q"}->param("code");
      if ($tmp &&
         ($tmp =~ m,^\d+$,)) {
         $brums = $tmp;
      }
   }
   if ($brums) {
      $json->{brums} = $brums;
      my $db = $self->{dbm}->getDBBackend($TICKETS);
      my $where = $self->{dbm}->Where_Pre($options->{curSession}, $MAC);
      push(@$where, "(".$BUCHUNGEN.$TSEP."brums = ".$json->{brums}.")");
      push(@$where, "(".$BUCHUNGEN.$TSEP.$ZAHLUNGSART."_".$UNIQIDCOLUMNNAME." = 2)"); # Brums
      my $retbuchungen = undef;
      if (defined($retbuchungen = $db->getDataSet({
         session  => $options->{curSession},
         table    => $BUCHUNGEN,
         wherePre => $where,
      })) && (ref($retbuchungen) eq "ARRAY") && (scalar(@{$retbuchungen->[0]}) == 1)) {
         my $ret = undef;
         if (defined($ret = $db->getDataSet({
            session  => $options->{curSession},
            table    => $TICKETS,
            id       => $retbuchungen->{$BUCHUNGEN.$TSEP.$TICKETS."_".$UNIQIDCOLUMNNAME} || die,
         })) && (ref($ret) eq "ARRAY") && (scalar(@{$ret->[0]}) == 1)) {
            $json->{ticketid} = $retbuchungen->[0]->[0]->{$BUCHUNGEN.$TSEP.$UNIQIDCOLUMNNAME};
            $json->{brumsok} = $retbuchungen->[0]->[0]->{$BUCHUNGEN.$TSEP."brumsok"} ? 1 : 0;
            $json->{count} = $ret->[0]->[0]->{$TICKETS.$TSEP."nomultiple"} ? 1 : scalar(keys %{$self->{dbm}->getTicketHistoryForTicket($options->{curSession}, $ret->[0]->[0]->{$TICKETS.$TSEP.$UNIQIDCOLUMNNAME})});
            $json->{price} = $self->{dbm}->getPricesForCount($json->{count} || 1);
            foreach my $column ($NAMECOLUMNNAME, "room", "beschreibung") {
               $json->{$column} = $ret->[0]->[0]->{$TICKETS.$TSEP.$column};
            }
            my $price = scalar($options->{connection}->{"q"}->param("payment") || undef);
            if ($price &&
               ($price =~ m,^\d+,)) {
               my $updatedid = undef;
               if ($updatedid = defined($db->updateDataSet({
                  table             => $BUCHUNGEN,
                  $UNIQIDCOLUMNNAME => $retbuchungen->{$BUCHUNGEN.$TSEP.$UNIQIDCOLUMNNAME} || die,
                  columns           => {
                     $BUCHUNGEN.$TSEP."brumsok" => 1,
                     $BUCHUNGEN.$TSEP."payment" => $price,
                  },
                  session           => $options->{curSession},
               })) =~ m,^\d+$,) {
                  $json->{brumsok} = 1;
               } else {
                  my $error = "Error reactivating mac entry ".$ret->[0]->[0]->{$TICKETS.$TSEP.$UNIQIDCOLUMNNAME}.": ".($updatedid||"UNDEF");
                  $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape($error));
                  Log($error, $WARNING);
               }
            }
         }
      }
   }
   $options->{response}->content_type("text/html");
   $options->{response}->header("Access-Control-Allow-Origin" => "*");
   if ($json) {
      ${$options->{content}} .= to_json($json);
   } else {
      ${$options->{content}} .= "No data.\n";
   }
}

sub ticketInfo {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless (!$moreparams) {
      Log("DBManager: ticketprint: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.":id:".$options->{id}."!", $ERROR);
      return 0;
   }
   # TODO:XXX:FIXME: Richtig machen...
   $options->{curSession}->{$USERSTABLENAME.$TSEP.$CUSTOMER."_".$UNIQIDCOLUMNNAME} = 1;
   $options->{curSession}->{$USERSTABLENAME.$TSEP.$UNIQIDCOLUMNNAME} = 1;
   my $json = undef;
   my $mac = $options->{connection}->{"q"}->param("mac");
   unless ($mac) {
      my $error = "No mac!";
      $options->{response}->content_type("text/html");
      ${$options->{content}} .= $error;
      Log($error, $ERROR);
      return;
   }
   my $where = $self->{dbm}->Where_Pre($options->{curSession}, $MAC);
   push(@$where, "(".$MAC.$TSEP."address"." = '".uc($mac)."')");
   #push(@$where, "(".$MAC.$TSEP."autodel = 1)");
   #push(@$where, "(".$MAC.$TSEP.$DELETEDCOLUMNNAME." = '1')");
   my $db = $self->{dbm}->getDBBackend($MAC);
   my $ret = undef;
   if (defined($ret = $db->getDataSet({
      session  => $options->{curSession},
      table    => $MAC,
      wherePre => $where,
   })) && (ref($ret) eq "ARRAY") && (scalar(@{$ret->[0]}))) {
      $json = $ret->[0];
   }
   $options->{response}->content_type("text/html");
   if ($json) {
      ${$options->{content}} .= to_json($json);
   } else {
      ${$options->{content}} .= "No data.\n";
   }
}

sub ticketExport {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{curSession} && $options->{table}) {
      Log("DBManager: ticketprint: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.":id:".$options->{id}."!", $ERROR);
      return 0;
   }
   my $curtabledef = $self->{dbm}->getTableDefiniton($options->{table});
   my $ret = undef;
   my $db = $self->{dbm}->getDBBackend($options->{table});
   my $wherePre = $self->{dbm}->Where_Pre($options->{curSession}, $options->{table});
   push(@$wherePre, join(" OR ", map { "(".$options->{table}.$TSEP.$self->{dbm}->getIdColumnName($options->{table})." = ".$_.")" } grep { /^\d+$/ }  @{$options->{ids}}))
      if (@{$options->{ids}});
   my $pwd = `pwd`;
   chomp($pwd);
   $pwd = "..".$pwd."/";
   #die $pwd;
   if (defined($ret = $db->getDataSet({
      session  => $options->{curSession},
      table    => $options->{table},
      #id       => $options->{id},
      wherePre => $wherePre,
   })) && (ref($ret) eq "ARRAY")) {
      if (scalar(@{$ret->[0]})) {
         my $doc = "";
         foreach my $curline (@{$ret->[0]}) {
            if ($curline->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"}) {
               my $x = $self->{gui}->replacer(
                  CGI::unescape($curline->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"}), {
                     %$curline,
                     'ticketstreet' => $self->{dbm}->{config}->{ticketstreet} || "Unbekannt",
                     'ticketplz' => $self->{dbm}->{config}->{ticketplz} || "",
                     'ticketcity' => $self->{dbm}->{config}->{ticketcity} || "",
                     'ticketid' => $self->{dbm}->{config}->{ticketid} || "",
                     'path' => $pwd,
                     sessionid => $options->{connection}->{sessionid},
                  }
               );
               # TODO:FIXME:XXX: Irgenwas macht da <br>s rein!!!!
               $x =~ s/<br>//g;
               print "VOrlage:".$x."\n";
               $doc .= $x;
            } else {
               Log("Keine Vorlage gefunden!")
            }
         }
         $self->showHTMLDocumentAsPDF({
            usewkhtmltopdf => 1,
            winname    => "tagebuch_".$options->{id},
            wintitle   => "Ticketausdruck #".$options->{id},
            htmlout    => $doc,
            connection => $options->{connection},
            curSession => $options->{curSession},
            winicon    => "icon",
         });
      } else {
         Log("No lines: ".scalar(@{$ret->[0]}), $ERROR);
      }
   } else {
      Log("DBManager: onNewLineServer: GET ".$options->{table}." FAILED SQL Query failed.", $WARNING);
   }
}

sub ticketprint {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{curSession} && $options->{table} && $options->{id}) {
      Log("DBManager: ticketprint: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.":id:".$options->{id}."!", $ERROR);
      return 0;
   }
   unless ($options->{id} =~ /^\d+$/) {
      #$poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 300 100 ".CGI::escape("Keine Vorlage ausgewählt!"));
      return 0;
   }
   if (defined(my $err = $self->{dbm}->checkRights($options->{curSession}, $ACTIVESESSION, $options->{table}, $options->{id}))) {
      $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("ticketprint ACCESS DENIED\n"));
      Log("DBManager: ticketprint: GET: ACCESS DENIED: ".$err->[0], $err->[1]);
      return 0;
   }
   my $curtabledef = $self->{dbm}->getTableDefiniton($options->{table});
   my $ret = undef;
   my $db = $self->{dbm}->getDBBackend($options->{table});
   my $pwd = `pwd`;
   chomp($pwd);
   $pwd = "..".$pwd."/";
   #die $pwd;
   if (defined($ret = $db->getDataSet({
      session  => $options->{curSession},
      table    => $options->{table},
      id       => $options->{id},
      wherePre => $self->{dbm}->Where_Pre($options->{curSession}, $options->{table}),
   })) && (ref($ret) eq "ARRAY")) {
      if (scalar(@{$ret->[0]}) == 1) {
         if ($ret->[0]->[0]->{$options->{table}.$TSEP.$UNIQIDCOLUMNNAME} ne $options->{id}) {
            $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("ticketprint INTERNAL ERROR\n"));
            Log("DBManager: ticketprint: GET: BAD IDs: ".$ret->[0]->[0]->{$options->{table}.$TSEP.$UNIQIDCOLUMNNAME}." != ".$options->{id});
            return 0;
         }
         #my $ticketprint = undef;
         #my $table = undef;
         #if (($ret->[0]->[0]->{$options->{table}.$TSEP.$BOXES."_".$UNIQIDCOLUMNNAME}) &&
         #    ($ret->[0]->[0]->{$BOXES.$TSEP."ticketprint"})) {
         #   $ticketprint = $ret->[0]->[0]->{$BOXES.$TSEP."ticketprint"};
         #   $table = $BOXES;
         #   #$poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("Found ticketprint of box ".$ret->[0]->[0]->{$options->{table}.$TSEP.$BOXES."_".$UNIQIDCOLUMNNAME}."!"));
         #} elsif (($ret->[0]->[0]->{$options->{table}.$TSEP.$VERBUND."_".$UNIQIDCOLUMNNAME}) &&
         #         ($ret->[0]->[0]->{$VERBUND.$TSEP."ticketprint"})) {
         #   $ticketprint = $ret->[0]->[0]->{$VERBUND.$TSEP."ticketprint"};
         #   $table = $VERBUND;
         #   #$poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("Found ticketprint of verbund ".$ret->[0]->[0]->{$options->{table}.$TSEP.$VERBUND."_".$UNIQIDCOLUMNNAME}."!"));
         #} elsif (($ret->[0]->[0]->{$options->{table}.$TSEP.$CUSTOMER."_".$UNIQIDCOLUMNNAME}) &&
         #         ($ret->[0]->[0]->{$CUSTOMER.$TSEP."ticketprint"})) {
         #   $ticketprint = $ret->[0]->[0]->{$CUSTOMER.$TSEP."ticketprint"};
         #   $table = $CUSTOMER;
         #   #$poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("Found ticketprint of customer ".$ret->[0]->[0]->{$options->{table}.$TSEP.$CUSTOMER."_".$UNIQIDCOLUMNNAME}."!"));
         #}
         #if (defined($ticketprint) && $ticketprint && defined($table) && $table) {
         # TODO:XXX:FIXME: Vorlage kommt hier noch nur vom... user?!
         if ($ret->[0]->[0]->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"}) {
            my $x = $self->{gui}->replacer(
               CGI::unescape($ret->[0]->[0]->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"}), {
                  %{$ret->[0]->[0]},
                  'ticketstreet' => $self->{dbm}->{config}->{ticketstreet} || "Unbekannt",
                  'ticketplz' => $self->{dbm}->{config}->{ticketplz} || "",
                  'ticketcity' => $self->{dbm}->{config}->{ticketcity} || "",
                  'ticketid' => $self->{dbm}->{config}->{ticketid} || "",
                  'path' => $pwd,
                  sessionid => $options->{connection}->{sessionid},
               }
            );
            # TODO:FIXME:XXX: Irgenwas macht da <br>s rein!!!!
            $x =~ s/<br>//g;
            print "VOrlage:".$ret->[0]->[0]->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"}."\n";
            
            $self->showHTMLDocumentAsPDF({
               usewkhtmltopdf => 1,
               winname    => "tagebuch_".$options->{id},
               wintitle   => "Ticketausdruck #".$options->{id},
               htmlout    => $x,
               connection => $options->{connection},
               curSession => $options->{curSession},
               winicon    => "icon",
            });
            #$self->onHTMLPreview({
            #   table => $VORLAGE, #$table,
            #   id => $options->{id},
            #   curSession => $options->{curSession},
            #   value => $ret->[0]->[0]->{$VORLAGE."_".$UNIQIDCOLUMNNAME."_".$VORLAGE.$TSEP."ticketprint"},
            #   column => "ticketprint",
            #   curset => $ret->[0]->[0],
            #});
         } else {
            $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 300 100 ".CGI::escape("Keine Vorlage gefunden!"));
            return 0;
         }
      } else {
         Log("Too much or no lines: ".scalar(@{$ret->[0]}), $ERROR);
         $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("Can't find a ticketprint!"));
         return 0;
      }
   } else {
      Log("DBManager: onNewLineServer: GET ".$options->{table}." FAILED SQL Query failed.", $WARNING);
      $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("FAILED"));
      return 0;
   }
   return 1;
}

sub onSaveEditEntry {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{curSession} && $options->{table} && $options->{"q"}) {
      Log("onSaveEditEntry: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.": !", $ERROR);
      return undef;
   }
   my $ret = $self->SUPER::onSaveEditEntry($options);
   my $curtabledef = $self->{dbm}->getTableDefiniton($options->{table});
   unless ($options->{curSession}->{rights} & $MODIFY) {
      if ($options->{table} eq $TICKETS) {
         my $id = $options->{connection}->{"q"}->param($UNIQIDCOLUMNNAME) ||
                  $options->{connection}->{"q"}->param($self->{dbm}->getIdColumnName($options->{table}));
         if ($ret) {
            return $poe_kernel->yield(sendToQX => "destroy ".CGI::escape($options->{table}."_edit"))
               if $id;
            if ($self->ticketprint({
               curSession => $options->{curSession},
               table => $options->{table},
               id => $ret
            })) {
               $poe_kernel->yield(sendToQX => "destroy ".CGI::escape($options->{table}."_edit"));
            } else {
               $poe_kernel->yield(sendToQX => "unlock ".CGI::escape($options->{"q"}->param("oid")));
            }
         } else {
            $poe_kernel->yield(sendToQX => "showmessage ".CGI::escape("Internal error")." 400 200 ".CGI::escape("Can't find ticket..."));
         }
      }
   }
   return $ret;
}

sub onHTMLPreview {
   my $self = shift;
   my $options = shift;
   my $moreparams = shift;
   unless ((!$moreparams) && $options->{curSession} && $options->{table} && defined($options->{value}) && $options->{column}) {
      Log("onHTMLPreview: Missing parameters: table:".$options->{table}.":curSession:".$options->{curSession}.": !", $ERROR);
      return 0;
   }
   my $curtabledef = $self->{dbm}->getTableDefiniton($options->{table});
   my $suffix = "htmlpreview";
   if ($options->{column} eq "ticketprint") {
      $options->{curset} ||= {
         $TICKETS.$TSEP."room" => "4711",
         $TICKETS.$TSEP.$UNIQIDCOLUMNNAME => "0815",
         $TICKETS.$TSEP.$PASS => "einTollesPasswort",
         $TICKETS.$TSEP."mydate" => "24.12.2048",
         $TICKETS.$TSEP."beschreibung" => "Max Mustermann",
         $TICKETS.$TSEP."usehours" => 60
      };
      $options->{curset}->{$TICKETS.$TSEP."usehours"} ||= "Unbegrenzt";
   }
   my $ret = $self->SUPER::onHTMLPreview($options);
   if (exists($curtabledef->{columns}->{$options->{column}}) &&
       exists($curtabledef->{columns}->{$options->{column}}->{mode}) &&
      defined($curtabledef->{columns}->{$options->{column}}->{mode}) &&
             ($curtabledef->{columns}->{$options->{column}}->{mode} eq "pdf")) {
      $options->{curSession}->{cachedcontenttype} = "application/pdf";
      $options->{curSession}->{cached} = $self->{gui}->html2pdf($options->{curSession}->{cached});
   }
   return $ret;
}

1;
