<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\InstanceKey;
	use Mocha\Core\KnownAttributeGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;

	use Mocha\Core\OmsContext;
	use Mocha\Oms\MySQLDatabaseOms;

	use Mocha\UI\Renderers\HTML\HTMLRenderer;
	use Phast\CancelEventArgs;
	use Phast\RenderingEventArgs;
	use Phast\WebPage;

	class AttachmentPage extends WebPage
	{

		protected function OnInitializing(CancelEventArgs $re)
		{
			$this->Page->MasterPage->ClassReference->RequireLogin = false;
			return true;
		}

		protected function OnRendering(RenderingEventArgs $re)
		{
			parent::OnRendering($re);
			
			/**
			 * @var MySQLDatabaseOms
			 */
			$oms = mocha_get_oms();

			$tenantName = $this->Page->GetPathVariableValue("tenant");
			$instId = $this->Page->GetPathVariableValue("instid");
			$accessKey = $this->Page->GetPathVariableValue("accesskey");

			$inst = $oms->getInstanceByKey(InstanceKey::Parse($instId));

			$ext = "jpg";
			$contentType = $oms->getAttributeValue($inst, KnownAttributeGuids::ContentType);
			if ($contentType === "image/jpeg")
			{
				$ext = "jpg";
			}
			else if ($contentType == "image/svg" || $contentType == "image/svg+xml")
			{
				$ext = "svg";
			}
			$path = "/var/mocha/uploads/" . $inst->GlobalIdentifier->__toStringFormat(false, null, null) . "." . $ext;
			if (file_exists($path))
			{
				$fsz = filesize($path);

				header("HTTP/1.1 200 OK");
				header("Content-Type: " . $contentType);
				header("Content-Length: " . $fsz);
				
				readfile($path);
			}
			else
			{
				header("HTTP/1.1 404 Not Found");
			}
			exit();
		}

	}
?>