<?php
namespace Modules\Admin\CronJobs\Runner;

class Controller extends \App\Mvc\Controller\CLIAbstract
{

	/**
	 * This script is used to run a cronjob class
	 *
	 * During development, you may test a cronjob with
	 * 		CLI: - this should be ran in the tina root
	 * 			$ php -f 'disp.php' module=Admin/CronJobs/Runner action=run job=REPLACE_WITH_JOB_NAME executionType=develop-cli
	 *
	 * 		BROWSER:
	 * 			$ disp.php?module=Admin/CronJobs/Runner&action=run&job=REPLACE_WITH_JOB_NAME&executionType=develop-browser
	 */

	protected function initialize()
	{
		parent::initialize();
		$this->actionsCfg['run'] = [];
	}

	/**
	 * Action run
	 */

	public function actionRun($R)
	{
		//Valid execution types ('actionExecuteTask', 'cronScheduler', 'develop-cli', 'develop-browser')
		if (SHOW_DEBUGS && ($R['executionType'] == 'develop-browser')) {
			// simulate a console-like-interface
			echo <<<HTML
				<head>
					<style>
						body {
							background-color: #f8f8f8;
							color: #444444;
						}
						div[class^="type-"] {
						    display: flex;
    						flex-direction: row;
						}
						.type {
							order: -1;
							min-width: 50px;
							padding-right: 0.25em;
						}
						.time {
							order: -3;
						}
						.memory {
							order: -2;
							min-width: 3em;
							text-align: right;
							color: #666;
							padding-right: 0.25em;
						}
						.type-critical .type     { color: #dc3545; }
						.type-error .type        { color: #dc3545; }
						.type-info .type         { color: #888888; }
						.type-idle .type         { color: #17a2b8; }
						.type-warning .type      { color: #ffc107; }
						.type-success .type      { color: #28a745; }

						.type,
						.time {
							padding: 0 15px 0 0;
							font-weight: bold;
						}
						div {
							font-family: monospace;
							font-size: 12px;
							width: 100%;
							line-height:150%;
						}
					</style>
				</head>
				<body>
					<div>
HTML;

			session_write_close();
			$_SESSION = null;

			set_time_limit(60*60*12);	// 12h timelimit
		}

		$cron = \App\Cron\Main::getCronjobObj($R['job']);
		$cron->setExecutionType($R['executionType']);

		// start to write in cron job logs
		$cronJobLogs = new \App\Cron\Log();

		$cronUpdate = \Entity\CronJob::update($cron->getId());
		$cronUpdate->isQueued = 0;
		$cronUpdate->save();

		// add a new user trail to indicate the cronjob
		$trailItem = \App\UserTrailItem::create($this->getModule(), 'actionRun');
		\App\UserTrail::getInstance()->addItem($trailItem);

		// the actual execution
		$cron->execute();

		if ($R['logId']) {
			$logger = $cron->getLogger();

			// this piece of code is repetead somewhere else in the code
			$errorStatus = [];
			if ($logger->has('critical')) {
				$errorStatus[]= 'c';
			}
			if ($logger->has('error')) {
				$errorStatus[]= 'e';
			}
			if ($logger->has('warning')) {
				$errorStatus[]= 'w';
			}
			if ($logger->has('info')) {
				$errorStatus[]= 'i';
			}
			if ($logger->has('idle')) {
				$errorStatus[]= 'd';
			}
			if ($logger->has('waiting')) {
				$errorStatus[]= 'g';
			}
			if ($logger->has('success')) {
				$errorStatus[]= 's';
			}

			$cronJobLogs->update($R['logId'], [
				'status' => 		'ended',
				'errorStatus' => 	implode('', $errorStatus),
			]);
		}

		if (SHOW_DEBUGS && ($R['executionType'] == 'develop-browser')){
			echo <<<HTML
				</div>
			</body>
HTML;
		}

		// return blank response, each Cronjob outputs text as it goes, it doesn't use the Response objects
		return new \Engine\Mvc\Response\None();
	}

}