<?php
require_once(dirname(__FILE__)."/../../../Tools/controllers/TransformerController.php");

class RemoteController
{
	public static function Run ($type = "", $files = array())
	{
		$remoteCtrl = new RemoteController();
		$remoteCtrl->getOptions();

		if ($type == "") {
			return $remoteCtrl->options;
		}
		if (!in_array($type, array_keys($remoteCtrl->options))) {
			return "Falscher Aufruf";
		}
		return $remoteCtrl->getDetails($type, $files);
	}

	private $config;
	private $info;
	private $paths;
	
	private $options;

	private function __construct ()
	{
		$this->config = parse_ini_file(dirname(__FILE__) . "/../../../../GAPS.ini");
		$this->info = json_decode(file_get_contents($this->config['XML'] . "\\info\\info.json"), true);
		$this->paths = array(
			'Tasks' => dirname(__FILE__) . "/../../../..",
			'Starter' => $this->config['STARTER'] . "\\Batch",
			'Transformer' => $this->config['PORTAL'] . "\\System\\Models",
			'Impromptu' => $this->config['PORTAL'] . "\\System\\IQD",
			'Powerplay' => $this->config['PORTAL'] . "\\System\\Report",
			'Portal' => $this->config['XML'],
			'Logs' => dirname(__FILE__) . "/../../../../logs",
			'Prot' => $this->config['PORTAL'] . "\\System\\Prot"
		);
		if (isset($this->config['PROT'])) {
			$this->paths['Prot'] = $this->config['PROT'];
		}
	}

	public function getOptions ()
	{
		$this->options = array(
			'Tasks' => $this->getFilenames($this->paths['Tasks'], "*.bat", false),
			'Starter' => $this->getFilenames($this->paths['Starter'], "*.bat"),
			'Transformer' => $this->getFilenames($this->paths['Transformer'], "*.pyi"),
			'Impromptu' => $this->getFilenames($this->paths['Impromptu'], "*.imr"),
			'Powerplay' => $this->getFilenames($this->paths['Powerplay'] , "*.ppr"),
			'Portal' => $this->getFilenames($this->paths['Portal'], "*.xml"),
			'Logs' => $this->getFilenames($this->paths['Logs'], "*"),
			'Prot' => $this->getFilenames($this->paths['Prot'], "*.log")
		);
	}

	private function removePath (&$value, $key, $path)
	{
		$value = utf8_encode(str_replace($path . "\\", "", $value));
	}

	private function getFilenames ($path, $filter, $recursive = true, $isSubdir = false)
	{
		$path = realpath($path);
		$result = glob($path . "\\" . $filter);

		if ($recursive) {
			foreach(glob($path . "\\*", GLOB_ONLYDIR) as $subdir) {

				if ($subdir != $path && substr($subdir, -1) != ".") {
					$result = array_merge($result, $this->getFilenames($subdir, $filter, $recursive, true));
				}
			}
		}

		if (!$isSubdir) {
			array_walk($result, array($this, 'removePath'), $path);
		}
		return $result;
	}

	public function getDetails ($type, $files)
	{
		$result = array();
		foreach ($files as $file) {
			$fullname = realpath($this->paths[$type] . "\\" . $file);
			if (!file_exists($fullname)) {
				continue;
			}
			$fileinfo = $this->getFileInfo($fullname);
			$fileinfo = call_user_func(array($this, "getDetails" . $type), $fileinfo);

			$result[$file] = $fileinfo;
		}
		return $result;
	}
	
	private function getFileInfo ($filename) 
	{
		$result = array(
			'filename' => $filename,
			'exists' => file_exists($filename)
		);
		if ($result['exists']) {
			$result['size'] = filesize($filename);
			$result['modified'] = date('d.m.Y H:i', filemtime($filename));
			$result['days'] = $this->dateDiff(filemtime($filename));
		} else {
			$result['size'] = 0;
			$result['modified'] = "fehlt";
			$result['days'] = 0;
		}
		return $result;
	}

	private function getDetailsTasks ($fileinfo)
	{
		$info['contents'] = explode("\r\n", file_get_contents($fileinfo['filename']));
		return $info;
	}

	private function getDetailsStarter ($fileinfo)
	{
		$info['contents'] = explode("\r\n", file_get_contents($fileinfo['filename']));
		return $info;
	}

	private function getDetailsImpromptu ($fileinfo)
	{
		$filename = substr($fileinfo['filename'], 0, -3);

		$ext = array('csv', 'ims', 'iqd');
		foreach($ext as $e) {
			$fileinfo[$e] = $this->getFileInfo($filename . $e);
		}

		if ($fileinfo['iqd']['exists']) {
			$fileinfo['iqd']['newer'] = filemtime($fileinfo['filename']) <= filemtime($fileinfo['iqd']['filename']) + 20;
		}
		return $fileinfo;
	}
	
	

	private function getDetailsTransformer ($fileinfo)
	{
		$fileinfo['cube'] = TransformerController::GetCubeName($fileinfo['filename']);
		$fileinfo['mdc'] = $this->getFileInfo(realpath($this->config['PORTAL'] . "\\System\\Cube_out") . "\\" . $fileinfo['cube'] . ".mdc");
		return $fileinfo;
	}

	private function getDetailsPowerplay ($fileinfo)
	{
		$filename = substr($fileinfo['filename'], 0, -3);
		$ext = array('ppx', 'gif', 'pdf', 'csv', 'xls');
		foreach($ext as $e) {
			$fileinfo[$e] = $this->getFileInfo($filename . $e);
		}
		return $fileinfo;
	}

	private function getDetailsPortal ($fileinfo)
	{
		$filename = strtolower(basename($fileinfo['filename']));
		$users = array('*' => '');
		$structure = array('*' => '');
		$email = array('*' => '');
		$cube = array('*' => '');

		foreach ($this->info['versand'] as $e) {
			if (strtolower($e['Datei']) == $filename) {
				$users[$e['Benutzer']] = 1;
				$structure[$e['Struktur']] = 1;
				$email[$e['Empfaenger']] = 1;
				$cube[$e['Cube']] = 1;
			}
		}
		$fileinfo['type'] = (count($users) == 1) ? "Portal" : "Versand";

		if ($fileinfo['type'] == "Portal") {
			foreach ($this->info['reports'] as $e) {
				if (strtolower($e['Datei']) == $filename) {
					$users[$e['Benutzer']] = 1;
					$structure[$e['Struktur']] = 1;
					$cube[$e['Cube']] = 1;
				}
			}
		}
		$fileinfo['users'] = array_keys($users);
		$fileinfo['structure'] = array_keys($structure);
		$fileinfo['email'] = array_keys($email);
		$fileinfo['cube'] = array_keys($cube);

		sort($fileinfo['users']);
		sort($fileinfo['structure']);
		sort($fileinfo['email']);
		sort($fileinfo['cube']);

		return $fileinfo;
	}

	private function dateDiff ($timestamp, $now = "now")
	{
		return round((strtotime($now) - strtotime($timestamp)) / (24 * 60 * 60));
	}
}