<?php

use Mocha\Core\OmsContext;
use Mocha\UI\Renderers\HTML\HTMLRenderer;
use Phast\System;

require_once("mochacommon.inc.php");

System::$BeforeGetTenantNameHandler = function()
{
	$path = System::GetVirtualPath(false);
	if ($path[0] === "madi")
	{
		return $path[2];
	}
	return $path[0];
};

function requiresLogin($path)
{
	if ($path != null)
	{
		if ($path == "ots/{tenant}/services/{serviceName}/{version}/{command}")
		{
			return false;
		}
	}

	/*
	if (count($path) > 0)
	{
		if ($path[0] == "ots"
		|| $path[0] == "suv"
		|| $path[0] == "ccx")
		{
			echo("no");
			return false;
		}
	}
	*/
	return true;
}

System::$BeforeLaunchEventHandler = function($path)
{
	/**
	 * @var \Mocha\Oms\MySQLDatabaseOms
	 */
	$oms = mocha_get_oms();
	if (count($path) >= 1)
	{
		if ($path[0] == "madi")
		{
			return true;
		}
		else if ($path[0] == "suv")
		{
			if (count($path) == 2 && ($path[1] == "suvinfo.html" || $path[1] == "phpinfo.html"))
			{
				// 
				return true;
			}
			else
			{
				header("HTTP/1.1 404 Not Found");
				echo ("Not Found");
				return false;
			}
		}
		else if ($path[0] == "scripts")
		{
			return true;
		}
	}

	if (count($path) == 0)
	{
		System::Redirect("~/" . System::$Configuration["Application.DefaultTenant"], true);
		return false;
	}
	
	if ($path[0] == "madi")
	{
		$currentTenantName = $path[2];
	}
	else if ($path[0] == "ots")
	{
		$currentTenantName = $path[1];
	}
	else
	{
		$currentTenantName = $path[0];
	}
	$currentTenant = $oms->getTenantByName($currentTenantName);
	
	if ($currentTenant == null)
	{
		$ctx = new OmsContext();
		$html = new HTMLRenderer($ctx, true);
		$html->IncludeTopNavigationBar = false;
		$html->renderBeginErrorPage("Tenant not found", "Tenant not found");
		echo ("<p>The specified tenant does not exist or is not available.</p>");
		echo ("<p>We apologize for the inconvenience. If you are a MochaPowered customer and require additional assistance please contact the Designated Support Contact within your organization. Otherwise, please check back later.</p>");
		$html->renderEndErrorPage();
		return false;
	}
	else
	{
		$oms->setTenant($currentTenant);
		if (count($path) == 1)
		{
			System::Redirect("~/" . $path[0] . "/d/home.htmld", true);
			return false;
		}
	}
	return true;
};

?>