<?php

class BaseBackgroundJobHandler {

	protected $job = null;

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

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

		$this->initializeLog($hash);

		try {
			$this->setLanguage($params);

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

	/**
	 * Set language
	 *
	 * @param $params
	 */
	private function setLanguage($params)
	{

		// Get default language
		$languages = ClassRegistry::init('Language')->getLanguages();
		Configure::write('Config.Languages', $languages);
		$defaultLanguage = null;
		foreach($languages as $locale => $localeOptions) {
			if($localeOptions['Language']['is_default']) {
				$defaultLanguage = $locale;
				break;
			}
		}
		Configure::write('Config.language', $defaultLanguage);

		if(isset($params['locale'])) {
			Configure::write('Config.language', $params['locale']);
		}

	}

	/**
	 * 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;
	}

	/**
	 * Initialize log
	 *
	 * @param $hash
	 */
	private function initializeLog($hash)
	{
		$this->log = array(
			'log' => '',
			'hash' => $hash,
			'pid' => getmypid(),
			'background_job_id' => $this->job['BackgroundJob']['id'],
			'handler' => $this->job['BackgroundJob']['handler'],
			'started' => date('Y-m-d H:i:s')
		);

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

}