<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfCron Class
 *
 * Class to manage tasks.
 *
 * @package clearFusionCMS
 */
class cfCron {
	/**
	 * The database object.
	 *
	 * @var flDb
	 */
	protected $db;

	/**
	 * Construct the object.
	 *
	 * @param flDb $db The database object.
	 */
	function __construct($db) {
		$this->db = $db;
	}

	/**
	 * Add a task to the system.
	 *
	 * @param string $event The event to be triggered.
	 * @param int $rate The rate to trigger the event at in seconds.
	 * @return bool true if added; else false.
	 */
	function addTask($event, $rate) {
		$now = new flDate();
		return $this->db->insert('cf_crontasks', array('event' => $event, 'nextrun' => $now->toString(), 'runrate' => $rate));
	}

	/**
	 * Remove the task from the system.
	 *
	 * @param string $event The event to remove.
	 * @return bool true if the event was removed; else false.
	 */
	function removeTask($event) {
		return $this->db->delete('cf_crontasks', 'event=?', $event);
	}

	/**
	 *  Get a list of tasks ready to run and update their next run time.
	 *
	 * @return array Array of tasks ready to run.
	 */
	function getReadyTasks() {
		// Get the ready tasks
		$tasks = array();
		$t = new flDate();
		$result = $this->db->query('SELECT event FROM cf_crontasks WHERE nextrun<=?', $t->toString());
		while($row = $result->fetch())
			$tasks[] = $row['event'];

		// Update next run time
		if(count($tasks))
			$this->db->query("UPDATE cf_crontasks SET nextrun=DATE_ADD(?, INTERVAL runrate SECOND) WHERE nextrun<=?", $t->toString(), $t->toString());

		return $tasks;
	}
}
