<?php
/**
* File containing the override of the authentication for the Library.
*
* @version 1.0 Initialisation of this file
* @since 1.0 Core application's file
* 
* @author Eole 'eoledev at outlook . fr'
* 
* @todo Check with the API, the condition and test the revoke token implementation
*/

use GuzzleHttp\Client;
use OpenCloud\Common\Transport\HandlerStack;
use OpenCloud\Common\Transport\Middleware;
use OpenStack\Identity\v3\Service;
use OpenStack\Identity\v3\Api;
use OpenCloud\Common\Auth\Token;
use OpenCloud\Common\Transport\Utils;
use OpenStack\Identity\v3\Models;

/**
* genTokenOptions Class
*
* This class allow the generation of tokens for openstack, and to inject 
* those tokens into the library. Which allow to do a proper login only once
* and not for each request
*
*/
class genTokenOptions
{
	/** @var Array $optionsGlobal private, contains the options common for the different tokens */
	private $optionsGlobal;
	/** @var Array $backup private, contains all the informations about the different tokens. It contains the information send to the clients */
	private $backup = [];
	/** @var GuzzleHttp\Client $httpClient private, contains a default Client to construct some OpenStack library object */
	private $httpClient;
	
	private $directory = __DIR__;

	/**
	* genTokenOptions constructor
	*
	* @param Array $options Options to create the objects in the library
	*												AuthUrl is the main options required
	*
	* @return genTokenOptions Object
	*/
	public function __construct($options){
		
		$stack = HandlerStack::create();

		$httpClient = new Client([
		'base_uri' => Utils::normalizeUrl($options['authUrl']),
		'handler'  => $stack,
		]);
		
		$this->httpClient = $httpClient;
		
		$options['identityService'] = Service::factory($httpClient);
		
		$options['authHandler'] = function () use ($options) {
			return $options['identityService']->generateToken($options);
		};

		$this->optionsGlobal['Common'] = $options;
	}

	/**
	* Add a debug for the library
	*
	* @param array $options Debug options, cf library
	* @param HandlerStack $stack pointer to a HandlerStack object
	*
	* @return void
	*/
	private function addDebugMiddleware(array $options, HandlerStack &$stack)
	{
		if (!empty($options['debugLog'])
				&& !empty($options['logger'])
				&& !empty($options['messageFormatter'])
				) {
			$stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
		}
	}

	/**
	* Check the expiration time of a token
	*
	* @return boolean if the token is not expired
	*/
	public function checkToken(){
		return $this->backup['time'] > time();
	}
	
	/**
	* Generate a new token for the Identity service
	*
	* @return void
	*/
	public function genIdentityToken(){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'false';
		$options['catalogType'] = 'false';
		$options['region'] = 'RegionOne';
		
		//list($token, $baseUrl) = $options['identityService']->authenticate($options);
		$baseUrl = $options["authUrl"];
		$token = $options['identityService']->generateToken($options);
		
		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Identity', array('token' => $token, 'baseUrl' => $baseUrl ));
		
		$this->optionsGlobal['Identity'] = $options;
	}
	
	/**
	* Revoke the token for the Identity Service
	*
	* @return void
	*/
	public function revokeIdentityToken(){
		$token = $this->unserializeToken($this->backup['Identity']['token']);
		$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
		
	}
	
	/**
	* Load a token for the Identity Service
	*
	* @param String $opt serialized token
	*
	* @return void
	*/
	public function loadIdentityBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'false';
		$options['catalogType'] = 'false';
		$options['region'] = 'RegionOne';
		
		$this->backup['Identity'] = $opt;
		$token = $this->unserializeToken($this->backup['Identity']['token']);
		$baseUrl = $this->backup['Identity']['baseUrl'];
		
		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Identity', array('token' => $token, 'baseUrl' => $baseUrl ));		
		$this->optionsGlobal['Identity'] = $options;
		
	}
	
	/**
	* Generate a new token for the Image service
	*
	* @return void
	*/
	public function genImageToken(){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'glance';
		$options['catalogType'] = 'image';
		$options['region'] = 'RegionOne';
		
		list($token, $baseUrl) = $options['identityService']->authenticate($options);

		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Image', array('token' => $token, 'baseUrl' => $baseUrl ));
		
		$this->optionsGlobal['Image'] = $options;
	}
	
	/**
	* Revoke the token for the Image Service
	*
	* @return void
	*/
	public function revokeImageToken(){
		$token = $this->unserializeToken($this->backup['Image']['token']);
		$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
		
	}
	
	/**
	* Load a token for the Image Service
	*
	* @param String $opt serialized token
	*
	* @return void
	*/
	public function loadImageBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'glance';
		$options['catalogType'] = 'image';
		$options['region'] = 'RegionOne';
		
		$this->backup['Image'] = $opt;
		$token = $this->unserializeToken($this->backup['Image']['token']);
		$baseUrl = $this->backup['Image']['baseUrl'];
		
		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Image', array('token' => $token, 'baseUrl' => $baseUrl ));	
		$this->optionsGlobal['Image'] = $options;
	}
	
	/**
	* Generate a new token for the Metwork service
	*
	* @return void
	*/
	public function genNetworkToken(){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'neutron';
		$options['catalogType'] = 'network';
		$options['region'] = 'RegionOne';
		
		list($token, $baseUrl) = $options['identityService']->authenticate($options);

		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Network', array('token' => $token, 'baseUrl' => $baseUrl ));
		
		$this->optionsGlobal['Network'] = $options;
	}
	
	/**
	* Revoke the token for the Network Service
	*
	* @return void
	*/
	public function revokeNetworkToken(){
		$token = $this->unserializeToken($this->backup['Network']['token']);
		$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
		
	}
	
	/**
	* Load a token for the Network Service
	*
	* @param String $opt serialized token
	*
	* @return void
	*/
	public function loadNetworkBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'neutron';
		$options['catalogType'] = 'network';
		$options['region'] = 'RegionOne';
		
		$this->backup['Network'] = $opt;
		$token = $this->unserializeToken($this->backup['Network']['token']);
		$baseUrl = $this->backup['Network']['baseUrl'];
		
		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Network', array('token' => $token, 'baseUrl' => $baseUrl ));
		$this->optionsGlobal['Network'] = $options;
	}
	
	/**
	* Generate a new token for the Compute service
	*
	* @return void
	*/
	public function genComputeToken(){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'nova';
		$options['catalogType'] = 'compute';
		$options['region'] = 'RegionOne';
		
		list($token, $baseUrl) = $options['identityService']->authenticate($options);

		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Compute', array('token' => $token, 'baseUrl' => $baseUrl ));
		
		$this->optionsGlobal['Compute'] = $options;
	}
	
	/**
	* Revoke the token for the Compute Service
	*
	* @return void
	*/
	public function revokeComputeToken(){
		$token = $this->unserializeToken($this->backup['Compute']['token']);
		$this->optionsGlobal['Common']['identityService']->revokeToken($token->id);
		
	}
	
	/**
	* Load a token for the Compute Service
	*
	* @param String $opt serialized token
	*
	* @return void
	*/
	public function loadComputeBackup($opt){
		
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'nova';
		$options['catalogType'] = 'compute';
		$options['region'] = 'RegionOne';
		
		$this->backup['Compute'] = $opt;
		$token = $this->unserializeToken($this->backup['Compute']['token']);
		$baseUrl = $this->backup['Compute']['baseUrl'];
		
		$stack = HandlerStack::create();
		
		$stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $stack);
		
		$options['httpClient'] = new Client([
		'base_uri' => Utils::normalizeUrl($baseUrl),
		'handler'  => $stack,
		]);
		$this->saveBackup('Compute', array('token' => $token, 'baseUrl' => $baseUrl ));
		$this->optionsGlobal['Compute'] = $options;
	}

	/**
	* Save the token given a service name
	*
	* @param String $name name of the service to save
	* @param Array $data token and baseUrl for the service
	*
	* @return void
	*/
	private function saveBackup($name, $data){
		$token = $this->serializeToken($data["token"]);
		$ret = file_put_contents($this->directory."/projectTokenData/".$token['saved']["project"]["name"], serialize($token['saved']));
		if($ret === FALSE)
			die("Internal Server Error : File Rights");
		$this->backup['time'] = $token['time'];
		$this->backup["roles"] = $token["roles"];
		$this->backup["project"] = $token['saved']["project"]["name"];
		$this->backup["user"] = $token["user"];
		$this->backup[$name] = array('token' => $token["token"], 'baseUrl' => $data["baseUrl"] );
	}
	
	/**
	* Retrieve the tokens saved
	*
	* @return String tokens serialized
	*/
	public function getBackup(){
		return serialize($this->backup);
	}
	
	/**
	* Load tokens into the library
	*
	* @param String $back tokens serialized
	*
	* @return void
	*/
	public function loadBackup($back){
		
		$backup = unserialize($back);
		$this->backup['time'] = $backup['time'];
		$this->backup["roles"] = $backup["roles"];
		$this->backup["project"] = $backup["project"];
		$this->backup["user"] = $backup["user"];
		$this->loadComputeBackup($backup["Compute"]);
		$this->loadIdentityBackup($backup["Identity"]);
		$this->loadImageBackup($backup["Image"]);
		$this->loadNetworkBackup($backup["Network"]);
		
	}
	
	/**
	* Retrieve the common options for a service
	*
	* @param String $service name of the service
	*
	* @return array Options to create the library class corresponding to this service
	*/
	public function getOptions($service){
		return $this->optionsGlobal[$service];
	}
	
	/**
	* Serialize a given token
	*
	* @param Array $token token to be serialized
	*
	* @return String token serialized
	*/
	private function serializeToken($token){
		global $config;
		$tokenSerialized = [];
		$tokenSerialized["token"]["methods"] = serialize($token->methods);
		$tokenSerialized["roles"] = [];
		
		foreach($token->roles as $role){
			$tokenSerialized["roles"][$role->id]["links"] = serialize($role->links);
			$tokenSerialized["roles"][$role->id]["name"] = serialize($role->name);
		}

		$tokenSerialized["token"]["expires"] = serialize($token->expires);
		$tokenSerialized['saved']["project"]["domainId"] = serialize($token->project->domainId);
		$tokenSerialized['saved']["project"]["parentId"] = serialize($token->project->parentId);
		$tokenSerialized['saved']["project"]["enabled"] = serialize($token->project->enabled);
		$tokenSerialized['saved']["project"]["description"] = serialize($token->project->description);
		$tokenSerialized['saved']["project"]["id"] = serialize($token->project->id);
		$tokenSerialized['saved']["project"]["links"] = serialize($token->project->links);
		$tokenSerialized['saved']["project"]["name"] = $token->project->name;
		
		$tokenSerialized['saved']["catalog"] = array();
		foreach($token->catalog->services as $service){
			$tokenSerialized['saved']["catalog"][$service->id]["name"] = serialize($service->name);
			$tokenSerialized['saved']["catalog"][$service->id]["description"] = serialize($service->description);
			$tokenSerialized['saved']["catalog"][$service->id]["type"] = serialize($service->type);

			foreach($service->endpoints as $end){
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["interface"] = serialize($end->interface);
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["name"] = serialize($end->name);
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["serviceId"] = serialize($end->serviceId);
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["region"] = serialize($end->region);
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["links"] = serialize($end->links);
				$tokenSerialized['saved']["catalog"][$service->id]["endpoints"][$end->id]["url"] = serialize($end->url);
			}
			$tokenSerialized['saved']["catalog"][$service->id]["links"] = serialize($service->links);
		}
		$tokenSerialized["token"]["extras"] = serialize($token->extras);
		$tokenSerialized["user"]["domainId"] = serialize($token->user->domainId);
		$tokenSerialized["user"]["defaultProjectId"] = serialize($token->user->defaultProjectId);
		$tokenSerialized["user"]["id"] = serialize($token->user->id);
		$tokenSerialized["user"]["email"] = serialize($token->user->email);
		$tokenSerialized["user"]["enabled"] = serialize($token->user->enabled);
		$tokenSerialized["user"]["description"] = serialize($token->user->description);
		$tokenSerialized["user"]["links"] = serialize($token->user->links);
		$tokenSerialized["user"]["name"] = serialize($token->user->name);
		$tokenSerialized["token"]["issued"] = serialize($token->issued);
		$tokenSerialized["token"]["id"] = serialize($token->id);		
		$tokenSerialized['time'] = time()+$config['tokenTime']*60;

		return $tokenSerialized;
	}
	
	/**
	* Unserialize a token
	*
	* Unserialize a token and recreate the architecture of the library token
	*
	* @param String $tokenSerialized the token to be unserialized
	*
	* @return OpenCloud\Common\Auth\Token the token unserialized
	*/
	private function unserializeToken($tokenSerialized){
		$Saved = file_get_contents($this->directory."/projectTokenData/".$this->backup["project"]);
		if($Saved === FALSE)
			die("Internal Server Error : File Access");
		$Saved = unserialize($Saved);

		$api = new Api();
		$token = new Models\Token($this->httpClient, $api);
		$token->methods = unserialize($tokenSerialized["methods"]);
		$token->roles = [];
		
		foreach($this->backup["roles"] as $key => $role){
			$tmp = new Models\Role($this->httpClient, $api);
			
			$tmp->id = $key;
			$tmp->links = unserialize($role["links"]);
			$tmp->name = unserialize($role["name"]);
			
			$token->roles[] = $tmp;
		}
		
		$token->expires = unserialize($tokenSerialized["expires"]);
		$token->project = new Models\Project($this->httpClient, $api);
		$token->project->domainId = unserialize($Saved["project"]["domainId"]);
		$token->project->parentId = unserialize($Saved["project"]["parentId"]);
		$token->project->enabled = unserialize($Saved["project"]["enabled"]);
		$token->project->description = unserialize($Saved["project"]["description"]);
		$token->project->id = unserialize($Saved["project"]["id"]);
		$token->project->links = unserialize($Saved["project"]["links"]);
		$token->project->name = $Saved["project"]["name"];
		
		$token->catalog = new Models\Catalog($this->httpClient, $api);
		$token->catalog->services = [];

		foreach($Saved["catalog"] as $key => $service){
			$tmp = new Models\Service($this->httpClient, $api);
			
			$tmp->id = $key;
			$tmp->name = unserialize($service["name"]);
			$tmp->description = unserialize($service["description"]);
			$tmp->type = unserialize($service["type"]);
			$tmp->endpoints = [];

			foreach($service["endpoints"] as $key => $end){
				$tmpEnd = new Models\Endpoint($this->httpClient, $api);
				$tmpEnd->id = $key;
				$tmpEnd->interface = unserialize($end["interface"]);
				$tmpEnd->name = unserialize($end["name"]);
				$tmpEnd->serviceId = unserialize($end["serviceId"]);
				$tmpEnd->region = unserialize($end["region"]);
				$tmpEnd->links = unserialize($end["links"]);
				$tmpEnd->url = unserialize($end["url"]);
				$tmp->endpoints[] = $tmpEnd;
			}
			$tmp->links = unserialize($service["links"]);
			$token->catalog->services[] = $tmp;
		}
		
		$token->extras = unserialize($tokenSerialized["extras"]);
		$token->user = new Models\User($this->httpClient, $api);
		$token->user->domainId = unserialize($this->backup["user"]["domainId"]);
		$token->user->defaultProjectId = unserialize($this->backup["user"]["defaultProjectId"]);
		$token->user->id = unserialize($this->backup["user"]["id"]);
		$token->user->email = unserialize($this->backup["user"]["email"]);
		$token->user->enabled = unserialize($this->backup["user"]["enabled"]);
		$token->user->links = unserialize($this->backup["user"]["links"]);
		$token->user->name = unserialize($this->backup["user"]["name"]);
		$token->user->description = unserialize($this->backup["user"]["description"]);
		$token->issued = unserialize($tokenSerialized["issued"]);
		$token->id = unserialize($tokenSerialized["id"]);
		
		return $token;
	}
}
