<?php

class BackgroundJobLog extends CronnerAppModel {

	var $useTable = 'cron_background_job_logs';

	var $belongsTo = [
		'BackgroundJob' => [
			'className' => 'Cronner.BackgroundJob'
		]
	];

	/**
	 * Get total run count
	 *
	 * @return array|mixed|null
	 */
	public function getTotalRunCount() {
		return $this->find('count');
	}

	/**
	 * Get total failed count
	 *
	 * @return array|mixed|null
	 */
	public function getTotalFailedRunCount() {
		return $this->find('count', [
			'conditions' => [
				$this->alias . '.status' => false
			]
		]);
	}

	/**
	 * Get last failed runs
	 *
	 * @return array
	 */
	public function getLastFailed() {
		$failedRuns = [];
		$allJobs = $this->BackgroundJob->find('all');

		foreach ($allJobs as $job) {
			$lastRun = $this->getLastRun($job['BackgroundJob']['id']);
			if (!empty($lastRun) && $lastRun[$this->alias]['status'] == false) {
				$failedRuns[] = $lastRun;
			}
		}

		return $failedRuns;
	}

	/**
	 * Get last run for job with provided id
	 *
	 * @param $jobId
	 *
	 * @return array|mixed|null
	 */
	public function getLastRun($jobId) {
		return $this->find('first', [
			'conditions' => [
				$this->alias . '.cron_job_id' => $jobId
			],
			'order'      => [
				$this->alias . '.created' => 'DESC'
			]
		]);
	}

	/**
	 * Get last runs for job id
	 *
	 * @param     $jobId
	 * @param int $limit
	 *
	 * @return array|mixed|null
	 */
	public function getLastRuns($jobId, $limit = 20) {
		return $this->find('all', [
			'conditions' => [
				$this->alias . '.cron_job_id' => $jobId
			],
			'order'      => [
				$this->alias . '.created' => 'DESC'
			],
			'limit'      => $limit
		]);
	}

	/**
	 * Get running jobs
	 *
	 * @param null $jobId
	 *
	 * @return array|mixed|null
	 */
	public function getRunning($jobId = null) {
		$findType = 'all';
		$conditions = [
			$this->alias . '.finished' => null
		];

		if (!empty($jobId)) {
			$conditions[$this->alias . '.cron_job_id'] = $jobId;
			$findType = 'first';
		}

		return $this->find($findType, [
			'conditions' => $conditions
		]);
	}

	/**
	 * Download log
	 *
	 * @param $logId
	 *
	 * @return bool
	 */
	public function downloadLog($logId) {
		$jobLog = $this->find('first', $logId);

		// Create log files
		$logDestination = PLUGGIN_CRONNER_BACKGROUND_JOB_LOGS . $jobLog[$this->alias]['hash'] . DS;

		if (!is_dir($logDestination)) {
			mkdir($logDestination, 0777);
		}
		$zipLocation = dirname($logDestination) . DS . $jobLog[$this->alias]['hash'] . '.zip';

		// Put db log there
		file_put_contents($logDestination . 'main.log', $jobLog[$this->alias]['log']);

		//create the archive
		$zip = new ZipArchive();
		if ($zip->open($zipLocation, ZIPARCHIVE::CREATE) !== true) {
			return false;
		}

		// Add files to zip
		foreach (glob(PLUGGIN_CRONNER_LOG . $jobLog[$this->alias]['hash'] . '/*') as $file) {
			$zip->addFile($file, basename($file));
		}

		// Close the zip
		$zip->close();

		// Output zip to browser
		header('Content-Type: application/zip');
		header('Content-Disposition: attachment; filename="background-job-log-' . $jobLog[$this->alias]['created'] . '.zip"');
		readfile($zipLocation);
		unlink($zipLocation);
		die;

	}

}
