<?php

	namespace Mocha\UI\Renderers\HTML;

	use Mocha\Core\InstanceKey;
	use Mocha\Core\InstanceReference;
	use Mocha\Core\OmsContext;
	use Mocha\UI\Controls\InstanceBrowser;
	use Phast\System;
	use Phast\WebControlAttribute;
	use Phast\WebControls\AdditionalDetailWidget;

	class HTMLRenderer2 extends HTMLRenderer
	{
		public function __construct(OmsContext $context, bool $withoutOms = false)
		{
			parent::__construct($context, $withoutOms);
		}

		public function processPostback(InstanceReference $element) : array | bool
		{
			/**
			 * @var \Mocha\Core\Oms
			 */
			$oms = mocha_get_oms();

			$values = array();
			foreach ($_POST as $key => $value)
			{
				if (str_starts_with($key, "ec_"))
				{
					$fqecid = substr($key, 3);
					$values[$fqecid] = $value;
				}
			}

			$array = $this->OMS->processElement($element, $values);
			if ($array["result"] === "failure")
			{
				return false;
			}

			if (is_callable($this->ProcessPostbackFunction))
			{
				// call user-defined ProcessPostbackFunction
				return call_user_func($this->ProcessPostbackFunction, $this, $element, $array);
			}
			else
			{
				$dummy = [ ];
				if (!$this->processRelatedPostback($dummy, $element))
				{
					return false;
				}
			}

			if (count($this->FailedValidations) > 0)
				return false;

			if ($this->DebugMode)
			{
				echo ("debug mode done");
				die();
			}

			if (isset($_POST["ReturnToURL"]))
			{
				System::Redirect($_POST["ReturnToURL"]);
				return true;
			}
			return $array;
		}

		public function renderInitialElement($element)
		{
			$json = $this->OMS->getResponse(element: $element);
			$this->renderResponse($json["value"]);
		}

		public function renderResponse(array $json)
		{
			$title = "";
			if (array_key_exists("title", $json))
			{
				if (array_key_exists("label", $json["title"]))
				{
					$title = $json["title"]["label"];
				}
			}

			$this->renderBeginPage($title);

		echo ("<!-- ");
		print_r($json);
		echo (" -->");

			if (!array_key_exists("visible", $json["title"]) || $json["title"]["visible"] === true)
			{
				$this->renderPageHeader($title, null);
			}

			$this->renderBeginContent();

			$this->renderFragment($json);

			$this->renderEndContent();
			$this->renderEndForm();
			$this->renderEndPage();
		}
		
		public function renderTask(InstanceReference $task, ?InstanceReference $relatedInstance = null)
		{
			if ($_SERVER["REQUEST_METHOD"] == "POST")
			{

			}
			else
			{
				$json = $this->OMS->getResponse(element: $task);
				if ($json["result"] == "success") {
					$title = $json["value"]["title"]["label"];

					$this->renderResponse($json["value"]);
				}
			}
			echo ("renderTask: " . $task->InstanceKey);
			return;
		}

		private function renderTabContainer(array $json)
		{
			echo ("<div class=\"uwt-tabcontainer\">");
			echo ("<ul class=\"uwt-tabcontainer-tabs\">");
			$i = 0;
			foreach ($json["children"] as $c)
			{
				echo ("<li class=\"uwt-tabcontainer-tab uwt-visible");
				if ($i == 0)
				{
					echo (" uwt-selected");
				}
				echo ("\"><a href=\"#\">" . $c["label"] . "</a></li>");
				$i++;
			}
			echo ("</ul>");
			echo ("<div class=\"uwt-tabcontainer-tabpages\">");
			$i = 0;
			foreach ($json["children"] as $c)
			{
				echo ("<div class=\"uwt-tabpage uwt-visible");
				if ($i == 0)
				{
					echo (" uwt-selected");
				}
				echo ("\">");
				$this->renderFragment($c);
				echo ("</div>");
				$i++;
			}
			echo ("</div>");
			echo ("</div>");
		}

		public function renderFragment(array $json, $fqecidPrefix = "")
		{
		echo ("<!-- ");
			print_r($json);
		echo (" -->");

			// echo ("renderFragment:<br/>"); print_r($json);
			//print_r($json); die();
			$fqecid = $fqecidPrefix . $json["ecid"];
			// we do not yet know how to deal with fully-qualified ECIDs
			$fqecid = $json["ecid"];
			if ($json["visible"] === false)
			{
				return;
			}
			
			if ($json["widget"] == "root")
			{
				$this->renderFragment($json["body"]);
			}
			else if ($json["widget"] == "tabContainer")
			{
				$this->renderTabContainer($json);
			}
			else if ($json["widget"] == "grid")
			{
				echo ("<table class=\"uwt-listview mcx-element\" data-ecid=\"" . $json["ecid"] . "\" data-instance-id=\"" . $json["iid"] . "\">");
				echo ("<caption>");
				
				echo ("<div class=\"uwt-toolbar uwt-listview-controlbox\">");
				echo ("<a class=\"uwt-button\" href=\"#\" title=\"Download\"><i class=\"fa fa-download\"></i></a>");
				echo ("<a class=\"uwt-button uwt-toggle\" href=\"#\" title=\"Filter\"><i class=\"fa fa-filter\"></i></a>");
				echo ("<a class=\"uwt-button uwt-toggle\" href=\"#\" title=\"Chart\"><i class=\"fa fa-line-chart\"></i></a>");
				echo ("<a class=\"uwt-button uwt-toggle\" href=\"#\" title=\"Columns\"><i class=\"fa fa-columns\"></i></a>");
				echo ("<a class=\"uwt-button uwt-toggle\" href=\"#\" title=\"Expand\"><i class=\"fa fa-expand\"></i></a>");
				echo ("</div>");

				echo ("</caption>");
				echo ("<thead>");
				echo ("<tr>");
				foreach ($json["columns"] as $col)
				{
					if (isset($col["visible"]) && !$col["visible"])
					{
						continue;
					}
					
					echo ("<th data-ecid=\"" . $col["ecid"] . "\" data-instance-id=\"" . $col["iid"] . "\">");
					echo ("<label>" . $col["label"] . "</label>");
					echo ("</th>");
				}
				echo ("</tr>");
				echo ("</thead>");
				echo ("<tbody>");
				foreach ($json["rows"] as $row)
				{
					echo ("<tr>");
					foreach ($row["cellsMap"] as $key => $col)
					{
						if (isset($col["visible"]) && !$col["visible"])
						{
							continue;
						}

						echo ("<td data-ecid=\"" . $col["ecid"] . "\" data-instance-id=\"" . $col["iid"] . "\">");
						//print_r($col);
						$this->renderFragment($col);
						echo ("</td>");
					}
					echo ("</tr>");
				}
				echo ("</tbody>");
				echo ("</table>");
			}
			else if ($json["widget"] == "vbox")
			{
				echo ("<div class=\"uwt-layout-box uwt-orientation-vertical\">");
				foreach ($json["children"] as $child)
				{
					$this->renderFragment($child);
				}
				echo ("</div>");
			}
			else if ($json["widget"] == "image")
			{
				echo ("<div class=\"uwt-image\" style=\"background-image: url('" . System::ExpandRelativePath("~/attachment/" . $json["iid"] . "/" . $json["target"]) . "');");
				if (isset($json["width"]))
				{
					echo(" width: " . $json["width"] . ";");
				}
				if (isset($json["height"]))
				{
					echo(" height: " . $json["height"] . ";");
				}
				if (isset($json["horizontalAlignment"]) && $json["horizontalAlignment"] == "center")
				{
					echo(" margin-left: auto; margin-right: auto;");
				}
				echo("\">&nbsp;</div>");
			}
			else if ($json["widget"] == "fieldSet")
			{
				$emitFieldset = false;
				foreach ($json["children"] as $child)
				{
					if ($child["widget"] == "commandButton")
					{
						echo ("<button>" . $child["label"] . "</button>");
						continue;
					}
					else
					{
						if (!$emitFieldset)
						{
							echo ("<div class=\"uwt-formview mcx-element\" data-instance-id=\"" . $json["iid"] . "\" data-ecid=\"" . $fqecid . "\">");
						}
						$emitFieldset = true;
					}

					// $fqecidChild = $fqecidPrefix . $child["ecid"];
					$fqecidChild = $child["ecid"];
					
					echo ("<div class=\"uwt-formview-item mcx-elementcontent");
					if (!isset($child["label"]))
					{
						echo(" uwt-hide-label");
					}
					if (!isset($child["enabled"]) || $child["enabled"] == true)
					{
						echo(" mcx-editable");
					}
					if (isset($child["required"]) && $child["required"] == true)
					{
						echo(" mcx-required");
					}
					if ($child["widget"] == "grid")
					{
						echo (" mcx-element");
					}
					echo ("\" data-instance-id=\"" . $child["iid"] . "\" data-ecid=\"" . $child["ecid"] . "\">");
						
					echo ("<div class=\"uwt-formview-item-label\">");
					echo ("<label for=\"ec_" . $fqecidChild . "\">");
					echo ($child["label"]);
					echo ("</label>");
					echo ("</div>");

					echo ("<div class=\"uwt-formview-item-content\"");
					/*
					if (!isset($child["label"]))
					{
						echo(" colspan=\"2\"");
					}
					*/
					echo (">");
					$this->renderFragment($child, $fqecid . ":");
					echo ("</div>");
					echo ("</div>");
				}

				if ($emitFieldset) {
					echo ("</div>");
				}
			}
			else if ($json["widget"] == "text")
			{
				if ($json["enabled"] === false)
				{
					echo ("<span data-ecid=\"" . $json["ecid"] . "\">" . $json["value"] . "</span>");
				}
				else
				{
					echo ("<input id=\"ec_" . $fqecid . "\" name=\"ec_" . $fqecid . "\" type=\"text\" value=\"" . $json["value"] . "\"");
					if (isset($json["maximumLength"]))
					{
						echo ("maxlength=\"" . $json["maximumLength"] . "\"");
					}
					echo (" />");
				}
			}
			else if ($json["widget"] == "obscuredText")
			{
				echo ("<input id=\"ec_" . $fqecid . "\" name=\"ec_" . $fqecid . "\" type=\"password\" value=\"" . $json["value"] . "\" />");
			}
			else if ($json["widget"] == "monikerList")
			{
				$adw = new InstanceBrowser();
				$adw->Attributes[] = new WebControlAttribute("data-ecid", $json["ecid"]);
				if (isset($json["enabled"]) && $json["enabled"] == false)
				{
					$adw->Editable = false;
				}
				else
				{
					$adw->Editable = true;
				}
				if (isset($json["instances"]) && count($json["instances"]) > 0)
				{
					foreach ($json["instances"] as $json_inst)
					{
						if ($json_inst["widget"] == "moniker")
						{
							// $adw->SelectedInstances[] = $this->OMS->getInstanceByKey(InstanceKey::Parse($json_inst["instanceId"]));
							$uri = $json_inst["target"];
							if ($uri == "")
							{
								$uri = $this->makeSelfUri($json["selfUriTemplate"]);
							}
							$adw->SelectedInstances[] = new InstanceReference(null, InstanceKey::Parse($json_inst["instanceId"]), null, $json_inst["text"], $uri);
						}
					}
				}
				else
				{
					$adw->Text = $json["text"];
				}
				echo ("<!-- ");
				print_r($json);
				echo ("-->");
				$adw->Render();
			}
		}

		public function makeSelfUri(string $uriTemplate)
		{
			$uri_parts = explode("/", $uriTemplate);
			$uri_parts2 = array();
			$i = 0;
			foreach ($uri_parts as $part)
			{
				$uri_parts2[] = $part;
				if ($i == 1)
				{
					$uri_parts2[] = "d";
				}
				$i++;
			}
			$uri_parts2[count($uri_parts2) - 1] .= ".htmld";

			return implode("/", $uri_parts2);
		}
	}

?>