<?php

class BaseHandler {

	protected $job = null;

	private $log = null;

	/**
	 * Execute logic - should be implemented in subclasses
	 */
	public function execute() {
		return false;
	}

	/**
	 * Run job
	 *
	 * @param $job
	 * @return bool|void
	 */
	public function run($job, $hash)
	{
		$this->job = $job;

		$this->initializeLog($hash);

		try {
			return $this->execute();
		} catch(Exception $e) {
			$this->log($e->getMessage());
		}
		return false;
	}

	/**
	 * Log message
	 *
	 * @param $message
	 */
	protected function log($message)
	{
		$this->log['log'] .= $message . "\r\n";
	}

	/**
	 * Get log for database
	 * @return array
	 */
	public function getLog()
	{
		return $this->log;
	}

	private function initializeLog($hash)
	{
		$this->log = array(
			'log' => '',
			'hash' => $hash,
			'pid' => getmypid(),
			'cron_job_id' => $this->job['CronJob']['id'],
			'name' => $this->job['CronJob']['name'],
			'handler' => $this->job['CronJob']['handler'],
			'started' => date('Y-m-d H:i:s')
		);

		$saved = ClassRegistry::init('Cronner.CronJobLog')->save($this->log);
		$this->log['id'] = $saved['CronJobLog']['id'];
	}

}