<?php

use Mocha\Core\InstanceReference;
use Mocha\Core\KnownAttributeGuids;
use Mocha\Core\KnownInstanceGuids;
use Mocha\Core\KnownRelationshipGuids;
use Mocha\Oms\MySQLDatabaseOms;
use Phast\System;

function mocha_get_oms()
{
	global $oms;
	if ($oms === null)
	{
		$oms = new MySQLDatabaseOms(System::GetConfigurationValue("Database.ServerName"), System::GetConfigurationValue("Database.PortNumber"), System::GetConfigurationValue("Database.DatabaseName"), System::GetConfigurationValue("Database.UserName"), System::GetConfigurationValue("Database.Password"));
	}
	$oms->setCurrentUser(mocha_get_current_user());
	return $oms;
}
function mocha_get_current_user() : ?InstanceReference
{
	/**
	 * @var MySQLDatabaseOms
	 */
	global $oms; //! WE CANNOT CALL mocha_get_oms() HERE!

	$currentTenant = $oms->getTenant();
	if (isset($_SESSION["user_token_" . $currentTenant->ID]))
	{
		// SELECT FROM `Users` WHERE `Token` = $_SESSION["user_token"]
		$insts = $oms->getInstancesByAttributes(array
		(
			KnownAttributeGuids::Token => $_SESSION["user_token_" . $currentTenant->ID]
		));

		$currentUser = null;
		$loginEntry = null;
		if (count($insts) == 1)
		{
			$loginEntry = $insts[0];

			if ($loginEntry != null)
			{
				$users = $oms->getRelatedInstances($loginEntry, $oms->getInstanceByGlobalIdentifier(KnownRelationshipGuids::User_Login__has__User));
				if (count($users) == 1)
				{
					$currentUser = $users[0];
				}
			}

			if ($currentUser === null)
			{
				echo("returned null");
				die();
			}
			return $currentUser;
		}
	}
	return null;
}
/**
 * Initializes the SPOT timer into the specified WebPage.
 * 
 * @return bool true if the spot timer was initialized successfully; false otherwise.
 */
function mocha_init_spot_timer($pg) : bool
{
	if ($pg === null)
		return false;

	$literalSpotTimer = $pg->GetControlByID("literalSpotTimer");
	$spotTimerInitializationScript = $pg->GetControlByID("spotTimerInitializationScript");
	if ($literalSpotTimer === null || $spotTimerInitializationScript === null)
		return false;

	$spotTimerContent = "";
	$spotTimerScript = "";
	mocha_get_spot_timer_script($spotTimerContent, $spotTimerScript);

	$literalSpotTimer->Content = $spotTimerContent;
	$spotTimerInitializationScript->Content = $spotTimerScript;
	return true;
}
function mocha_get_spot_timer_script(&$spotTimerContent, &$spotTimerScript)
{
	$spotTimerContent = "";
	$spotTimerScript = "";

	if (file_exists("/etc/mocha/suvstart"))
	{
		$suv_start_time = trim(file_get_contents("/etc/mocha/suvstart"));
		$suv_start_time_d = new \DateTime($suv_start_time);
		$suv_start_time_d->setTimezone(new \DateTimeZone("UTC"));

		// this can be adjusted?
		$suv_end_time_d = $suv_start_time_d->add(new \DateInterval("PT10H"));
		$suv_end_time_d->setTimezone(new \DateTimeZone("UTC"));

		$suv_end_time = $suv_end_time_d->format('Y-m-d\TH:i:s\Z');

		$suv_current_time_d = new \DateTime();
		$interval = $suv_end_time_d->diff($suv_current_time_d);

		$spotTimerContent = $interval->h . ":" . $interval->i;

		$spotTimerScript = <<<EOT
		<script type="text/javascript">
		var spot_end_time = new Date('$suv_end_time');
		window.datediff = function(earlierDate, laterDate)
		{
			var interval = { };
			var a = earlierDate, b = laterDate;

			console.log(earlierDate);
			console.log(laterDate);

			const _MS_PER_DAY = 1000 * 60 * 60 * 24;
			// Discard the time and time-zone information.
			const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds());
			const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getHours(), b.getMinutes(), b.getSeconds());
		  
			console.log(utc2);
			console.log(utc1);

			var diffMS = (utc2 - utc1);

			console.log(diffMS);
			
			var secs = (diffMS / 1000) % 60;
			var mins = (diffMS / (1000 * 60)) % 60;
			var hrs = (diffMS / (1000 * 60 * 60)) % 24;
			
			interval =
			{
				"raw": diffMS,
				"seconds": Math.floor(secs),
				"minutes": Math.floor(mins),
				"hours": Math.floor(hrs)
			};
			return interval;
		};
		window.spot_timer_tick = function()
		{
			var spot_cur_time = new Date();
			var diff = datediff(spot_cur_time, spot_end_time);
			console.log(diff);
			document.getElementById('spot_timer').innerHTML = diff.hours + ':' + diff.minutes.toString().padStart(2, '0');

			window.setTimeout(spot_timer_tick, 60000);
		};
		window.addEventListener("load", function()
		{
			spot_timer_tick();
		});
		</script>
		EOT;
	}
}
?>