<?php
###############################################################################
# Cron.php
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace 	CodePunch\Config;
use CodePunch\Base\Util as UTIL;

###############################################################################

class Cron  {
	
	private $authentication 	= null;
	
	const UNKNOWN_PROCESSING	= 0;
	const QUEUE_PROCESSING		= 1;
	const LUSCH_PROCESSING		= 2;
	const REPORT_PROCESSING		= 4;
	const JOB_PROCESSING		= 8;
	
	###########################################################################
	
	public function __construct($auth=null) {
		$this->authentication = $auth;
	}
	
	###########################################################################
	
	public function getAuthentication() {
		return $this->authentication;
	}
	
	###############################################################################
	
	public function logConnection()
	{
		// TODO:
		// Add Queue Index and other stuff.
		
		$db = $this->getAuthentication()->getDatabase();
		$setup = new \CodePunch\Config\Settings($this->getAuthentication());
		
		$servertable = $db->getInstalledServersTableName();
		$server_name = $this->getAuthentication()->getServerID();
		$nowtime = date("Y-m-d H:i:s");
		$count = $db->getRowCount($servertable, "name=?", array($server_name));
		if ($count != false && $count == 1) 
			return $db->updateTable($servertable, array('last_seen_at'=>$nowtime), "name=?", array($server_name));
		else
			return $db->insertIntoTable($servertable, array('last_seen_at'=>$nowtime, 'name'=>$server_name));
	}
	
	###############################################################################
	
	public function preProcess($maxrows, $maxseconds, $start=0)
	{
		$maxseconds = $maxseconds < 5 ? 5 : $maxseconds;
		$maxseconds = $maxseconds > 50 ? 50 : $maxseconds;
		$this->logConnection();
		$responce = array();
		$responce['type'] = self::UNKNOWN_PROCESSING;
		$responce['processed'] = 0;
		$responce['attempted'] = 0;
		$responce['start'] = $start;
		$responce['maxrows'] = $maxrows;
		$responce['maxseconds'] = $maxseconds;
		$responce['rows'] = array();
		$responce['validate'] = $this->getAuthentication()->validateSession(false, false);
		
		if($responce['validate'] != \CodePunch\Config\Auth::VALID) {
			if(!UTIL::is_cli()) {
				$remotekey = UTIL::get_sanitized_request_string("key", "");
				if(!$this->getAuthentication()->isValidRemoteKey($remotekey))
					$responce['validate'] = \CodePunch\Config\Auth::INVALID;
				else
					$responce['validate'] = \CodePunch\Config\Auth::LIMITED;
			}
			else
				$responce['validate'] = \CodePunch\Config\Auth::VALID;
		}
		return $responce;
	}
	
	###############################################################################
	
	public function postProcess($responce)
	{
		// TODO:
		// Add Queue Index and other stuff.
		
		$db = $this->getAuthentication()->getDatabase();
		$setup = new \CodePunch\Config\Settings($this->getAuthentication());
		
		$servertable = $db->getInstalledServersTableName();
		$server_name = $this->getAuthentication()->getServerID();
		$nowtime = date("Y-m-d H:i:s");
		
		$cdata['last_seen_at'] = $nowtime;
		if(isset($responce['processed']) && isset($responce['type']) && $responce['type'] != self::UNKNOWN_PROCESSING) {
			if($responce['processed'] && ($responce['type'] & self::QUEUE_PROCESSING))
				$cdata['last_lookup_at'] = $nowtime;
		}
		
		$count = $db->getRowCount($servertable, "name=?", array($server_name));
		if ($count != false && $count == 1) 
			return $db->updateTable($servertable, $cdata, "name=?", array($server_name));
		else {
			$cdata['name'] = $server_name;
			return $db->insertIntoTable($servertable, $cdata);
		}
	}
	
	###############################################################################
	
	public function runJobs(&$responce)
	{
		if(UTIL::is_cli()) {
			$setup = new \CodePunch\Config\Settings($this->getAuthentication());
			$jobs = $setup->getPendingJobs();
			if($jobs !== false) {
				foreach($jobs as $job) {
					$parts = explode(";", $job);
					if(count($parts) >= 2) {
						$cmd = $parts[0];
						if($cmd == "add") {
							$regapi = $parts[1];
							if(isset($parts[2]))
								$cids = $parts[2];
							else
								$cids = "";
							if($regapi != "") {
								$regapis = explode(",", $regapi);
								$responce['added'] = 0;
								$responce['failed'] = 0;
								$responce['error'] = '';
								$import = new \CodePunch\DB\ImportManager($this->getAuthentication());
								foreach($regapis as $api) {
									$info = $import->importDomainsFromRegistrar($api, $cids);
									$responce['added'] += $info['added'];
								}
							}
						}
						else if($cmd == "report") {
							// Run the report and make it available for download.
							$rm = new \CodePunch\UI\ReportManager($this->getAuthentication());
							$columns = explode(",", $parts[1]);
							$query = isset($parts[2]) ? $parts[2] : "";
							$params = explode("|", isset($parts[3]) ? $parts[3] : "");
							$sidx = isset($parts[4]) ? $parts[4] : "";
							$sord = isset($parts[5]) ? $parts[5] : "";
							$name = isset($parts[6]) ? $parts[6] : "";
							$uid = isset($parts[7]) ? intval($parts[7]) : 0;
							$delimiter = isset($parts[8]) ? $parts[8] : ",";
							$description = isset($parts[9]) ? $parts[9] : ",";
							if(!isset($responce['reports']))
								$responce['reports'] = 0;
							$responce['reports'] += $rm->runCSVReport($uid, $columns, $query, $params, $name, $sidx, $sord, $delimiter, $description);
						}
						else if($cmd == "task") {
							$methodname = $parts[1];
							if(method_exists('\CodePunch\Config\Tasks', $methodname)) {
								$count = call_user_func(array('\CodePunch\Config\Tasks', $methodname), $this->getAuthentication());
								if($count)
									AUDIT::add($db, AUDIT::GENERIC_ACTION, "RDAP Servers ($count) filled in TLD Table", "");
							}
						}
					}
				}
				$responce['type'] |= self::JOB_PROCESSING;
				return true;
			}
		}
		return false;
	}
	
	###############################################################################
	
	public function process($maxrows=50, $maxseconds=20, $start=0, $forcereports=false)
	{
		$responce = $this->preProcess($maxrows, $maxseconds, $start);
		if($responce['validate'] != \CodePunch\Config\Auth::INVALID) {
			if($this->runJobs($responce) === false) {
				if(\CodePunch\UI\ReportManager::run($this->getAuthentication(), $responce, $forcereports) === false) {
					\CodePunch\LU\LookupManager::run($this->getAuthentication(), $responce);
				}
			}
			$this->postProcess($responce);
		}
		return $responce;
	}
}
