<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides OSB task running capabilities.
 *
 * @package    OSB
 * @subpackage Task
 * @category   Controllers/Admin
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Task_Task extends Controller_Task {
	/**
	 * List all tasks
	 */
	public function action_list() {
		$output = '';
		$to = ORM::factory('task');
		$tm = 'list_'.$this->request->param('id');

		if (! method_exists($to,$tm))
			throw new Kohana_Exception('Unknown Task List command :command',array(':command'=>$tm));

		$output .= sprintf('%2s %30s %21s %21s %40s',
			'ID','Command','Last Run','Next Run','Description');
		$output .= "\n";

		foreach ($to->$tm() as $t) {
			$output .= sprintf('%2s %30s %21s %21s %40s',
				$t['task']->id,
				$t['task']->command,
				$t['task']->display('date_run'),
				Config::datetime($t['next']),
				$t['task']->display('description')
			);

			$output .= "\n";
		};

		$this->response->body($output);
	}

	public function action_run() {
		if ($id = $this->request->param('id')) {
			$to = ORM::factory('task',$id);
			$to->run();

		} else {
			$tlo = ORM::factory('task');
			$t = time();

			foreach ($tlo->list_active() as $to)
				if ($to['next'] < $t)
					$to['task']->run();
		}
	}
}
?>
