#!/usr/bin/env perl
use strict;
use warnings;
use SMT::Agent::Utils;
use XML::XPath;
use XML::XPath::XMLParser;

sub jobhandler
{
  my ($jobtype, $jobid, $args, $verbose) =  @_;

  SMT::Agent::Utils::logger("jobhandler for report job called", $jobid);
  SMT::Agent::Utils::logger("report runs jobid \"$jobid\"", $jobid);

  # check whether this handler can handle requested jobtype
  SMT::Agent::Utils::error("wrong job handler: \"report\" cannot handle \"$jobtype\"", $jobid) if ( $jobtype ne "report" );

  my $xpQuery = XML::XPath->new(xml => $args);
  eval { SMT::Agent::Utils::error("no argument section found for this job", $jobid) unless ( $xpQuery->exists('/arguments[1]')); };

  my $argSet;
  eval { $argSet = $xpQuery->find('/arguments[1]') };
  SMT::Agent::Utils::error("xml data is not parsable", $jobid) if ($@);
  SMT::Agent::Utils::error("too many argument sections found for this job", $jobid) unless ( (defined $argSet) && ($argSet->size() == 1) );

  my $arg = $argSet->pop();
  my @jobids = ();
  my $jobidSet;
  eval { $jobidSet = $xpQuery->find('/arguments[1]/jobid') };
  SMT::Agent::Utils::error("xml data is not parsable", $jobid) if ($@);
  foreach my $_n ($jobidSet->get_nodelist()) {
      push (@jobids, $_n->string_value()) if (defined $_n);
  }

  # try to import SMT server modules to find out if we are running on a SMT server
  eval {
      require SMT::CLI;          # for database connection
      require SMT::Job::Result;  # request job results
  };
  SMT::Agent::Utils::error("Report job can only run on a SMT server. Could not find SMT server installation. Error message: $@", $jobid ) if ($@);

  # connect to database
  my ($cfg, $dbh) = SMT::CLI::init();
  SMT::Agent::Utils::error("Could not connect to the SMT server database. Error message: $@", $jobid ) unless defined $dbh;

  my $jr = SMT::Job::Result->new({ 'dbh' => $dbh });
  my $resxml = $jr->getResults( [@jobids], undef, { asXML => 1, checkupstream => 1 } );

  return (
    stdout   => '',
    stderr   => '',
    exitcode => (defined $resxml) ? 0 : 1,
    success  => (defined $resxml) ? "true" : "false",
    result   => $resxml ? ("\n".$resxml) : undef,
    message  => (defined $resxml) ? "Report job successfully finished" : "Report job failed."
  );

}

SMT::Agent::Utils::logger("successfully loaded handler for jobtype \"report\"");

return 1;

