<?php



error_reporting(E_ALL);



use Idearia\Logger;



set_time_limit(240);



require_once(__DIR__ . "/../src/load.php");



Logger::$log_level = 'debug';

Logger::$write_log = true;

Logger::$log_dir = __DIR__ . "/../logs";

Logger::$log_file_name = 'worker-run';

Logger::$log_file_extension = 'log';

Logger::$log_file_append = true;

Logger::$print_log = false;



$jobQueue = new n0nag0n\Job_Queue('mysql', [

	'mysql' => [

		'use_compression' => false,

	]

]);



$PDO = new PDO('mysql:dbname=' . INTDB_DATABASE . ';host=' . INTDB_HOST, INTDB_USER, INTDB_PASS);

$jobQueue->addQueueConnection($PDO);



$pipeline = htmlspecialchars($_GET["pipeline"]) ?? "";





$jobQueue->watchPipeline($pipeline);

$intQueueRunner = new QueueRunner();





while (true) {

	$job = $jobQueue->getNextJobAndReserve();



	if (empty($job)) {

		break;

	}



	$payload = json_decode($job['payload'], true);



	try {

		// Logger::debug( "Running task id={$job['id']} from pipe={$pipeline}" );

		Logger::$log_file_name = "job-{$job['id']}-pipe-{$pipeline}";

		$result = $intQueueRunner->run($pipeline, $payload);

		



		if ($result === true) {

			// Logger::$log_file_name = 'worker-run';

			echo "SUCCESS ID={$job['id']} PIPE={$pipeline}::{$payload['itemAction']} ITEM=[{$payload['itemId']}] LOG job-{$job['id']}-pipe-{$pipeline}<br>\r\n";

			Logger::info( "Success task id={$job['id']} from pipe={$pipeline}" );

			$jobQueue->deleteJob($job);

			break;

		} else {

			echo "FAIL ID={$job['id']} PIPE={$pipeline}::{$payload['itemAction']} ITEM=[{$payload['itemId']}] LOG job-{$job['id']}-pipe-{$pipeline}<br>\r\n";

			// Logger::$log_file_name = 'worker-run';

			Logger::error( "Fail task id={$job['id']} from pipe={$pipeline}" );

			$jobQueue->buryJob($job);

			break;

		}

	} catch (Exception $e) {

		// Logger::$log_file_name = 'worker-run';

			echo "ERROR ID={$job['id']} PIPE={$pipeline}::{$payload['itemAction']} ITEM=[{$payload['itemId']}] LOG job-{$job['id']}-pipe-{$pipeline}<br>\r\n";

		Logger::error( "Error task id={$job['id']} from pipe={$pipeline}" );

		Logger::error( "Error: {$e->getMessage()}" );

		$jobQueue->buryJob($job);

	}

	break;

}