<?php

/**
 * This PHP file is the webapp auth api that gets loaded into an iframe
 * to allow it to integrate with configuration options from the webapp plugin
 */

include_once('jsconfig.php');

header("Content-type: text/html; charset=utf-8");
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Kopano WebApp Auth API</title>
		<script src="../js/jquery-1.6.2.min.js"></script>
		<script type="text/javascript">
				<?= PLUGIN_SPREEDWEBRTC_JS_CONFIG ?>
				var sessionid;
				var access_token;
				var refreshTimeout;

				var request_token = function (code, process_response, process_failure) {
					var url = config.webappAuthTokenUrl;
					var posting = $.post( url, { 
						code: code, 
						client_id: 'zarafa_webmeetings',
						client_secret: '',
						redirect_uri: '',
						grant_type: 'authorization_code' } );
					posting.done(function( data, textStatus, xhr ) {
						console.log( data );
						if(typeof data =='object') {
							console.log("request_token success JSON");
						}
						var IS_JSON = true;
						try
						{
							var json = $.parseJSON(data);
						}
						catch(err)
						{
							IS_JSON = false;
						}                
						if(IS_JSON) {
							console.log("request_token success JSON text");
							process_response(data);
						} else {
							console.log("request_token failed");
							process_failure(data);
						}
					}).fail(function() {
						console.log("request_token failed");
						process_failure();
					});
				};

				var request_webmeetings_data = function (access_token, process_response, process_failure) {
					var url = config.webappAuthWebmeetingsDataUrl;
					var posting = $.post( url, { 
						access_token: access_token,
						client_id: 'zarafa_webmeetings',
						client_secret: '' } );
					posting.done(function( data, textStatus, xhr ) {
						console.log( data );
						if(typeof data =='object') {
							console.log("request_webmeetings_data success JSON");
						}
						var IS_JSON = true;
						try
						{
							var json = $.parseJSON(data);
						}
						catch(err)
						{
							IS_JSON = false;
						}                
						if(IS_JSON) {
							console.log("request_webmeetings_data success JSON text");
							process_response(data);
						} else {
							console.log("request_webmeetings_data failed");
							process_failure(data);
						}
					}).fail(function() {
						console.log("request_token failed");
						process_failure();
					});
				};

				/**
				 * Event handler for post messages from WebApp
				 *
				 * @param {Event} e postMessage event
				 */
				var onPostMessage = function (e) {
					var message = e.data;
					var code;

					// check if the message comes from a valid origin
					if (config.spreedDomain === e.origin) {
						// Handle postMessages from the webapp
						switch (message.type) {
							case "request_token":
								switch (message.request_token.type) {
									case "zarafa":
										code = "zarafasession";
										break;
									case "code":
										code = message.request_token.code;
										break;
								}
								request_token(
									code,
									function(response) {
										if (response && response.success == true) {
											var json = response;
											access_token = response.access_token;
											console.log("request_token success JSON text");
											parent.postMessage({
												type: "access_token",
												access_token: {
													access_token: access_token
												}
											},
											config.spreedDomain);
											refreshTimeout = setTimeout(function() {
												console.log("access_token refresh TTL reached - sending refresh_access_token request.");
												// Request a new authentication object from WebApp
												parent.postMessage({
													type: "refresh_access_token",
													refresh_access_token: message.request_token
												},
												config.spreedDomain);
											}, response.expires_in / 100 * 80 * 1000);
										}
									},
									// failure case
									function() {
										parent.postMessage({type: "requestLogin",}, config.spreedDomain);
									}
								)
								break;
							case "requestAuthentication":
								// TODO check first if we are already authenticated
								var access_token = message.requestAuthentication.access_token;

								request_webmeetings_data(
									access_token, 
									function(response) {
										if (response && response.success == true) {
											console.log("request_webmeetings_data OK");
											parent.postMessage({
												type: "authentication",
												authentication: response.webmeetings_data
											},
											config.spreedDomain);
										}
									},
									// failure case
									function() {
										parent.postMessage({type: "requestLogin",}, config.spreedDomain);

									}
								);
								break;
							case "requestLogout":
								// display login iframe
								parent.postMessage({type: "requestLogin",}, config.spreedDomain);
								break;
						}
					}
				};

				// Listen to post message event from the Kopano spreed plugin
				window.addEventListener('message', onPostMessage);
				parent.postMessage({type: "hello",}, config.spreedDomain);
		</script>
	</body>
</html>
