<?php

class HandlerRegistry {

	/**
	 * Get all available handlers
	 *
	 * @return array
	 */
	public static function getAllHandlers()
	{
		$handlers = App::objects('Console/Handler', APP . 'Console' . DS . 'Handler' . DS, false);

		$formatted = array();

		foreach($handlers as $handler) {
			if($handler == 'AppCronHandler') {
				continue;
			}
			$formatted[$handler] = str_replace('Handler', '', $handler);
		}

		return $formatted;
	}

	/**
	 * Get handler by name
	 *
	 * @param $handlerName
	 * @return mixed
	 * @throws CronHandlerNotFoundException
	 */
	public static function getHandler($handlerName)
	{
		App::import('Console/Handler', $handlerName);
		if(!class_exists($handlerName)) {
			throw new CronHandlerNotFoundException(__('Cron handler "%s" not found!', $handlerName));
		}
		return new $handlerName();
	}

	/**
	 * Get one time job handler
	 *
	 * @param $handlerName
	 * @return mixed
	 * @throws CronHandlerNotFoundException
	 */
	public static function getBackgroundJobHandler($handlerName)
	{
		App::import('Console/BackgroundJobHandler', $handlerName);
		if(!class_exists($handlerName)) {
			$handlerName = $handlerName . 'Handler';
			App::import('Console/BackgroundJobHandler', $handlerName);
			if(class_exists($handlerName)) {
				return new $handlerName();
			} else {
				throw new CronHandlerNotFoundException(__('Cron handler "%s" not found!', $handlerName));
			}
		}
		return new $handlerName();
	}
}

class CronHandlerNotFoundException extends Exception {}