<?php
App::uses('CronnerAppController', 'Cronner.Controller');
App::uses('HandlerRegistry', 'Cronner.Handler');
class CronJobsController extends CronnerAppController {

	var $components = array('Api');

	/**
	 * Pass additional variables to form view
	 *
	 * @param null $id
	 */
	public function form($id = null)
	{
		$this->set('handlers', (new HandlerRegistry())->getAllHandlers());
		parent::form($id);
	}

	/**
	 * Pass additional variables to view
	 *
	 * @param null $id
	 */
	public function view($id)
	{
		parent::view($id);

		$vars = array(
			'lastRun' => $this->{$this->modelClass}->getLastRun(),
			'nextRun' => $this->{$this->modelClass}->getNextRunTime(),
			'currentlyRunning' => $this->{$this->modelClass}->getCurrentlyRunning(),
			'lastRuns' => $this->{$this->modelClass}->getLastRuns()
		);
		$this->set($vars);
	}

	/**
	 * Download log
	 *
	 * @param $logId
	 */
	public function downloadLog($logId)
	{
		$this->{$this->modelClass}->downloadLog($logId);
	}


	public function trigger($jobId)
	{
		App::import('Cronner.Handler', 'Runner');
		$runner = new Runner();

		$job = $this->{$this->modelClass}->find('first', $jobId);

		if(empty($job)) {
			exit;
		}

		$runner->trigger($job);

		$this->Api->build('response', array(
			'success' => true
		));
	}

	/**
	 * Get job status - long pooling
	 *
	 * @param $jobId
	 */
	public function status($jobId)
	{
		session_write_close();

		$job = $this->{$this->modelClass}->find('first', $jobId);

		$clientRunning = $this->request->data['running'] == 'true' ? true : false;

		if(empty($job)) {
			exit;
		}

		$steps = 50;
		do {

			$currentlyRunning = $this->{$this->modelClass}->getCurrentlyRunning();
			$serverRunning = !empty($currentlyRunning);

			$steps--;
			usleep(100000);
		} while($this->request->data['running'] != null && $clientRunning == $serverRunning && $steps > 0);

		if(empty($currentlyRunning)) {
			$this->Api->build('response', array(
				'running' => false,
				'data' => null
			));
		}


		$output = shell_exec('ps -p ' . $currentlyRunning['CronJobLog']['pid'] . ' -o %cpu,%mem');
		$output = trim($output);
		$outputItems = explode(' ', $output);
		$outputItems = array_values(array_filter($outputItems));

		$stats = array(
			'cpu' => trim($outputItems[2]),
			'memory' => trim($outputItems[3])
		);

		$this->Api->build('response', array(
			'running' => true,
			'data' => array(
				'pid' => $currentlyRunning['CronJobLog']['pid'],
				'started' => $currentlyRunning['CronJobLog']['started'],
				'cpu' => $stats['cpu'],
				'memory' => $stats['memory']
			)
		));

	}

}
