<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\KnownAttributeGuids;
	use Mocha\Oms\Oms;
	use Mocha\Core\InstanceKey;
	use Mocha\Core\InstanceReference;
	use Mocha\Core\KnownClassGuids;
	use Mocha\Core\KnownInstanceGuids;
	use Mocha\Core\KnownRelationshipGuids;
	use Mocha\Core\OmsContext;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\UUID;
	use Phast\WebPage;

	class FlowControllerPage extends WebPage
	{
		private function buildElementContentJSON(Oms $oms, InstanceReference $subEC)
		{
			$ecDataType = $oms->getRelatedInstance($subEC, KnownRelationshipGuids::Element_Content__has__Instance);
			$ary = array
			(
				"ecid" => $subEC->InstanceKey->__toString()
			);
			$widget = "";
			if ($ecDataType != null)
			{
				$dataTypeClass = $oms->getParentClass($ecDataType);
				$ary["ecdt"] = $ecDataType->InstanceKey->__toString();
				if
				(
					$dataTypeClass->GlobalIdentifier->__is_equal(UUID::parse(KnownClassGuids::TextAttribute))
					|| $dataTypeClass->GlobalIdentifier->__is_equal(UUID::parse(KnownClassGuids::NumericAttribute))
					|| $dataTypeClass->GlobalIdentifier->__is_equal(UUID::parse(KnownClassGuids::DateAttribute))
				)
				{
					$widget = "text";
				}
				else if ($dataTypeClass->GlobalIdentifier->__is_equal(UUID::parse(KnownClassGuids::BooleanAttribute)))
				{
					$widget = "checkbox";
				}
				else if ($oms->is_a($dataTypeClass, UUID::parse(KnownClassGuids::Clasz)))
				{
					$widget = "monikerListInput";
					if (($oms->getAttributeValue($subEC, KnownAttributeGuids::Singular))
					|| ($oms->getAttributeValue($ecDataType, KnownAttributeGuids::Singular)))
					{
						$ary["multiselect"] = false;
					}
					else
					{
						$ary["multiselect"] = true;
					}
				}
			}

			$ary["widget"] = $widget;
			return $ary;
		}

		protected function OnInitializing(\Phast\CancelEventArgs $e)
		{
			header("Content-Type: application/json");
			
			$oms = mocha_get_oms();
			$tenantName = System::GetTenantName();

			$user = $oms->getCurrentUser();
			if ($user === null)
			{
				header("HTTP/1.1 401 Unauthorized");
				$json = array
				(
					"result" => "failure",
					"message" => "Please log in to perform this action"
				);
				echo (json_encode($json));
				exit();
			}

			$jsonInputStr = file_get_contents("php://input");
			$jsonInput = json_decode($jsonInputStr, true);

			global $context;
			$contextsReset = false;
			if ($context === null)
			{
				$contextsReset = true;
				$context = new OmsContext();
			}

			$fqecid = $jsonInput["ecid"];
			$ecids = explode(":", $fqecid);
			$ecid = $ecids[count($ecids) - 1];

			$parentECIDs = substr($fqecid, 0, strripos($fqecid, ":"));

			$ec = $oms->getInstanceByKey(InstanceKey::Parse($ecid));
			if ($ec === null)
			{
				header ("HTTP/1.1 404 Not Found");
				echo ("{ \"result\": \"failure\", \"message\": \"invalid inst id " . $ecid . " (inst not found)\" }");
				return;
			}
			
			header ("HTTP/1.1 200 OK");
			
			$element = $oms->getRelatedInstance($ec, KnownRelationshipGuids::Element_Content__has__Instance);
			if ($oms->is_a($element, KnownClassGuids::Element))
			{
				$contents = [];
				$elementContents = $oms->getRelatedInstances($element, KnownRelationshipGuids::Element__has__Element_Content);
				foreach ($elementContents as $subEC)
				{
					$contents[] = $this->buildElementContentJSON($oms, $subEC);
				}
			}
			else if ($oms->is_a($element, KnownClassGuids::BooleanAttribute))
			{
				$value = $jsonInput["value"];
				$oms->setSessionAttributeValue($context, $ec, $value);
				$changes = array();

				$ecDDOs = $oms->getRelatedInstances($ec, KnownRelationshipGuids::Element_Content__has__EC_Dynamic_Display_Option);
				foreach ($ecDDOs as $ecDDO)
				{
					$addsDisplayOptions = $oms->getRelatedInstances($ecDDO, KnownRelationshipGuids::Dynamic_Display_Option__add__Display_Option);
					$removesDisplayOptions = $oms->getRelatedInstances($ecDDO, KnownRelationshipGuids::Dynamic_Display_Option__remove__Display_Option);
					$modifiesElementContents = $oms->getRelatedInstances($ecDDO, KnownRelationshipGuids::EC_Dynamic_Display_Option__modifies__Element_Content);

					foreach ($modifiesElementContents as $modifiesElementContent)
					{
						$change = array
						(
							"ecid" => $parentECIDs . ":" . $modifiesElementContent->InstanceKey->__toString(),
							"addsDisplayOptions" => [],
							"removesDisplayOptions" => []
						);
						foreach ($addsDisplayOptions as $addsDisplayOption)
						{
							$change["addsDisplayOptions"][] = array("iid" => $addsDisplayOption->InstanceKey->__toString() );
						}
						foreach ($removesDisplayOptions as $removesDisplayOption)
						{
							$change["removesDisplayOptions"][] = array("iid" => $removesDisplayOption->InstanceKey->__toString() );
						}
						$changes[] = $change;
					}
				}
				
				if ($ecid == "56$217")
				{
					//!FIXME: how to represent this in mocha db with dynamic EC changes / dependent ECs
					
					//! 3$259		Element Content.has EC Dynamic Display Option
					//! used for the EC triggering the DDO on the affected EC

					// e.g. 56$217 has DDO for controlling the two textboxen

					//! 3$261		Element Content.modified by EC Dynamic Display Option
					//! used for the EC affected by the dynamic DO

					// e.g. the aforementioned DDO modifies 56$218, 56$219

				}

				$retval = array
				(
					"result" => "success",
					"contextsReset" => $contextsReset,
					"value" => $oms->getSessionAttributeValue($context, $ec),
					"changes" => $changes
				);
				echo (json_encode($retval));
				exit();
			}
			else
			{
				echo ("{ \"result\": \"failure\", \"message\": \"not an element\" }");
				exit();
			}

			$json = array
			(
				"result" => "success",
				"item" => array
				(
					"widget" => "row",
					"contents" => $contents
				)
			);
			echo(json_encode($json));

			$e->Cancel = true;
		}
	}

?>