<?php
require_once(dirname(__FILE__)."/AscParseController.php");
require_once(dirname(__FILE__)."/GapsXmlInfoController.php");

class PowerplayController
{
	private $publishDir;
	private $tempDir;

	private $ppxFile;
	private $report;
	private $app;

	private $cubeFile;
	public $ReportName;

	public static function Run ($argv)
	{
		if (count($argv) <= 2) die();
		$action =  $argv[1];

		switch ($action) {
			case "remove-queries":
				PowerplayController::RemoveQueries($argv);
				break;
			case "add-queries":
			case "untermengen":
				PowerplayController::AddQueries($argv);
				break;
			case "cube-name":
				PowerplayController::CubeName($argv[2]);
				break;
			case "rename":
				PowerplayController::Rename($argv);
				break;
			default:
			case "export":
				PowerplayController::Export($argv);
				break;
		}
	}

	public static function Export ($params) 
	{
		$pprFile = $params[2];
		$export = (count($params) > 3) ? $params[3] : "jpg";
		$publishDir = (count($params) > 4) ? $params[4] : "";
		$exportFile = (count($params) > 5) ? $params[5] : "";
		$cubeName = (count($params) > 6) ? $params[6] : "";

		$pprCtrl = new PowerplayController($publishDir);
		if (!$pprCtrl->OpenReport($pprFile, $cubeName)) {
			echo "{$pprFile} kann nicht geoeffnet werden!\r\n";
			die();
		}

		switch ($export) {
			case "asc":
				$pprCtrl->SaveAsAsc();
				break;
			case "json":
				$ascFile = $pprCtrl->SaveAsAsc();
				$apCtrl = new AscParseController();
				$apCtrl->Run($ascFile, $exportFile);
				break;
			case "pdf":
				$pprCtrl->SaveAsPdf($exportFile);
				break;
			case "ppr":
				$pprCtrl->SaveAsPpr($exportFile);
				break;
			case "ppx":
				$pprCtrl->SaveAsPpx($exportFile);
				break;
			case "xls":
				$pprCtrl->SaveAsXls($exportFile);
				break;

			case "jpg":
			default:
				$pprCtrl->PublishImages();
				break;
		}
		$pprCtrl->CloseReport();
		$pprCtrl->Quit();
	}
	
	public static function RemoveQueries ($params) 
	{
		$reportDir = realpath($params[2]);
		$suffix = $params[3] . ".";
		$dimensions = explode(",", $params[4]);
		
		$pprCtrl = new PowerplayController($reportDir);
		$dir = dir($reportDir);
		
		while ($file = $dir->read()) {
			if (stripos($file, $suffix)) {
				$fullFilename = $reportDir . "\\" . $file;
				if ($pprCtrl->OpenReport($fullFilename)) {
					$pprCtrl->RemoveReportQueryItems($dimensions);
					$pprCtrl->SaveAsPpr(str_replace(".ppx", ".ppr", str_replace($suffix, ".", $fullFilename)));
					$pprCtrl->CloseReport();
					echo "  {$file}: Untermengen entfernt.\r\n";
				}
			}
		}
		$pprCtrl->Quit();		
	}

	public static function AddQueries ($params)
	{
		$pprCtrl = new PowerplayController("");
		$pprCtrl->OpenReport($params[2]);
		$pprCtrl->AddReportQueryItems("AH-Gruppe", "Serviceberater", "Mainz - Kastel");
		$pprCtrl->CloseReport();
		$pprCtrl->Quit();
	}

	public static function CubeName ($file)
	{
		$pprCtrl = new PowerplayController(dirname(__FILE__));
		$pprCtrl->OpenReport($file);
		$cubeFile = $pprCtrl->GetCubeFilename();
		$pprCtrl->CloseReport();
		$pprCtrl->Quit();
		return $cubeFile;
	}
	
	public static function Rename ($params)
	{
		if (count($params) < 5) {
			echo "Aufruf: powerplay.bat rename [Report-Pfad] [Cubename] [Neuer Pfad und Name]\r\n";
			return;
		}
		$reportPath = realpath($params[2]);
		$cubeName = $params[3];
		$newPathAndName = realpath($params[4]);
		
		if (substr($cubeName, -4) == ".mdc") {
			$cubeName = substr($cubeName, 0, -4);
		}
		
		$pprCtrl = new PowerplayController($reportPath);

		$gxiCtrl = new GapsXmlInfoController();
		$reports = $gxiCtrl->getExistingReportFiles("1", $reportPath . "\\", false, $cubeName);
		
		foreach ($reports as $report => $cube) {
			$reportFile = $reportPath . "\\" . $report . ".ppr";
			if (!file_exists($reportFile)) {
				$reportFile = $reportPath . "\\" . $report . ".ppx";
			}
			if (!file_exists($reportFile)) {
				continue;
			}
			
			if ($pprCtrl->OpenReport($reportFile, $newPathAndName)) {
				$pprCtrl->Save();
				$pprCtrl->CloseReport();
			}
		}
		$pprCtrl->Quit();
	}

	public function __construct ($publishDir)
	{
		$this->publishDir = $publishDir;
		$this->tempDir = $this->publishDir ."\\temp\\";
		@mkdir($this->publishDir, 0777, true);
		@mkdir($this->tempDir);
		
		$this->app = new COM("CognosPowerplay.Application");
	}

	public function OpenReport ($ppxFile, $cubeName = "")
	{
		$this->ppxFile = $ppxFile;
		if (preg_match('/[\\\\\\/]([^\\\\\\/]*)\.pp[rx]$/i', $this->ppxFile, $match)) {
			$this->ReportName = $match[1];
		} else {
			$this->ReportName = substr($this->ppxFile, 0, -4);
		}
		if (preg_match("/_graf$/i", $this->ReportName)) {
			$this->ReportName = substr($this->ReportName, 0, -5);
		}
		if (!file_exists($this->ppxFile)) {
			return false;
		}
		try {
			if ($cubeName != "") {
				$this->report = new COM("CognosPowerplay.Report");
				$this->report->Open($this->ppxFile, $cubeName);
			} else {
				$this->report = $this->app->Reports->Open($this->ppxFile);
			}
		}
		catch (Exception $e) {
			echo "Could not open file '" . $this->ppxFile . "'\r\n";
			echo $e->getMessage() . "\r\n";
			return false;
		}
		return true;
	}

	public function CloseReport ()
	{
		$this->report->Close();
	}

	public function Quit ()
	{
		$this->app->Quit();
	}
		
	public function RemoveReportQueryItems ($dimensions) 
	{
		$items = $this->report->ReportQueries->Count;
		$i = 1;
		while ($i <= $items) {
			$dim = $this->report->ReportQueries->Item($i)->Dimension;
			if (in_array($dim, $dimensions)) {
				$this->report->ReportQueries->Item($i)->Remove(false);
				$items -= 1;
			} else {
				$i += 1;
			}
		}
	}

	public function AddReportQueryItems ($dimension, $level, $category)
	{
		$parent = $this->report->ReportQueries->Add(2);
		$parent->Category($category);
		$parent->LowestLevel = false;
		$parent->Execute();

		$query = $this->report->ReportQueries->Add(3);
		$query->Name = $level . " " . $category;
		$query->Dimension = $dimension;
		$query->Level($level);
		$query->Find($parent);
		$query->Execute();
		$query->AddToReport(1, 1, 3);

	}

	
	public function GetCubeFilename () 
	{
		$this->cubeFile = $this->report->CubeName;
		return $this->cubeFile;
	}
	
	public function GetCellValue ($row, $col)
	{
		try {
			return $this->report->CellValue($row, $col);
		}
		catch (Exception $e) {
			echo $e->getMessage() . "\r\n";
			return 0;
		}
	}

	public function SaveAsPdf ($filename = "", $layers = null)
	{
		if ($filename == "") {
			$filename = $this->ReportName;
		}
		$layerCount = $this->report->Layers->Count;
		if ($layers == null) {
			$layers = range(0, $layerCount);
		}

		foreach ($layers as $layer) {
			if ($layer > $layerCount) {
				continue;
			}

			$pdfFile = "{$this->publishDir}\\{$filename}_{$layer}.pdf";
			$pdf = $this->report->PDFFile($pdfFile, true);

			if ($layer == 0) {
				$pdf->SaveEntireReport = true;
				$pdf->SaveAllCharts = true;

				$pdf->IncludeLegend = false;
				$pdf->AxisOnAllPages = true;
				$pdf->ChartTitleOnAllPages = false;

			} else {
				$this->report->Layers->Item($layer)->Activate();
				if ($this->report->Rows->Count == 0) {
					continue;
				}

				$pdf->SaveEntireReport = false;
				$pdf->SaveAllCharts = false;

				$pdf->IncludeLegend = true;
				$pdf->ChartTitleOnAllPages = true;
				$pdf->AxisOnAllPages = true;

				$pdf->SetListOfLayersToSave($this->report->Layers->Subset($layer, $layer));
				$pdf->SetListOfRowsToSave($this->report->Rows);
			}
			@unlink($pdfFile);
			$pdf->Save();
		}
	}

	public function SaveAsXls ($filename = "")
	{
		if ($filename == "") {
			$filename = "{$this->publishDir}\\{$this->ReportName}_0.xls";
		}
		@unlink($filename);
		$this->report->SaveAs($filename, 4);
		return $filename;
	}

	public function SaveAsPpx ($filename = "")
	{
		if ($filename == "") {
			$filename = substr($this->ppxFile, 0, -4) . ".ppx";
		}
		@unlink($filename);
		$this->report->SaveAs($filename, 5);
		return $filename;
	}

	public function SaveAsAsc ($filename = "")
	{
		if ($filename == "") {
			$filename = "{$this->publishDir}\\{$this->ReportName}.asc";
		}
		@unlink($filename);
		$this->report->SaveAs($filename, 3);
		return $filename;
	}
	
	public function Save ()
	{
		if (substr($this->ppxFile, -4) == ".ppr") {
			$this->SaveAsPpr();
		} else {
			$this->SaveAsPpx();
		}
	}
	
	public function SaveAsPpr ($filename = "")
	{
		if ($filename == "") {
			$filename = substr($this->ppxFile, 0, -4) . ".ppr";
		}
		@unlink($filename);
		$this->report->SaveAs($filename, 1);
		return $filename;
	}
	
	public function PublishImages ()
	{
		$this->clearTempDir();
		$this->report->Visible = true;		

		$this->report->Publish($this->tempDir, false, true, true);
		$files = glob($this->tempDir . "*.jpg");

		foreach ($files as $i => $filename) {
			$layer = $i + 1;
			$renameTo = "{$this->publishDir}\\{$this->ReportName}_{$layer}.jpg";
			@unlink($renameTo);
			rename($filename, $renameTo);
			$imageObject = imagecreatefromjpeg($renameTo);
			imagegif($imageObject, substr($renameTo, 0, -4) . '.gif');
		}
	}

	private function clearTempDir ()
	{
		shell_exec("del /F /Q " . $this->tempDir . "*.*");
	}
}