<?php

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

class genTokenOptions
{
	private $optionsGlobal;
	
	private $stack;
	private $backup = [];
	private $httpClient;

	public function __construct($options){
		
		$this->stack = HandlerStack::create();

		$httpClient = new Client([
            'base_uri' => Utils::normalizeUrl($options['authUrl']),
            'handler'  => $this->stack,
        ]);
		
		$this->httpClient = $httpClient;
		
        $options['identityService'] = Service::factory($httpClient);
		
		$options['authHandler'] = function () use ($options) {
			return $options['identityService']->generateToken($options);
        };
		
		$this->optionsGlobal['Common'] = $options;
	}
 
		/**
     * @codeCoverageIgnore
     */
    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']));
        }
    }
	
	public function genComputeToken(){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'nova';
		$options['catalogType'] = 'compute';
		$options['region'] = 'RegionOne';
		
		list($token, $baseUrl) = $options['identityService']->authenticate($options);
		//var_dump($token);		
		//$stack = HandlerStack::create();
        $this->stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $this->stack);
		
		$options['httpClient'] = new Client([
            'base_uri' => Utils::normalizeUrl($baseUrl),
            'handler'  => $this->stack,
        ]);
		$this->backup['Compute'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );
		
		$this->optionsGlobal['Compute'] = $options;
	}
	
	public function loadComputeBackup($opt){
		
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'nova';
		$options['catalogType'] = 'compute';
		$options['region'] = 'RegionOne';
		
		//list($token, $baseUrl) = $options['identityService']->authenticate($options);
		$this->backup['Compute'] = unserialize($opt);
		//var_dump($this->backup['Compute']);
		$token = $this->unserializeToken($this->backup['Compute']['token']);
		$baseUrl = $this->backup['Compute']['baseUrl'];
		
		//$stack = HandlerStack::create();
    
		$this->stack->push(Middleware::authHandler($options['authHandler'], $token));
		
		$this->addDebugMiddleware($options, $this->stack);
		
		$options['httpClient'] = new Client([
            'base_uri' => Utils::normalizeUrl($baseUrl),
            'handler'  => $this->stack,
        ]);
		$this->backup['Compute'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );		
		$this->optionsGlobal['Compute'] = $options;
	}

	public function getBackup($service){
		return serialize($this->backup[$service]);
	}
	
	public function getOptionsCompute(){
		return $this->optionsGlobal['Compute'];
	}
	
	private function serializeToken($token){
		$tokenSerialized = [];
		$tokenSerialized["methods"] = serialize($token->methods);
		$tokenSerialized["roles"] = [];
		//var_dump($token->roles);
		foreach($token->roles as $role){
			$tokenSerialized["roles"][serialize($role->name)]["links"] = serialize($role->links);
			$tokenSerialized["roles"][serialize($role->name)]["id"] = serialize($role->id);
		}	
		$tokenSerialized["expires"] = serialize($token->expires);
		$tokenSerialized["project"]["domainId"] = serialize($token->project->domainId);
		$tokenSerialized["project"]["parentId"] = serialize($token->project->parentId);
		$tokenSerialized["project"]["enabled"] = serialize($token->project->enabled);
		$tokenSerialized["project"]["description"] = serialize($token->project->description);
		$tokenSerialized["project"]["id"] = serialize($token->project->id);
		$tokenSerialized["project"]["links"] = serialize($token->project->links);
		$tokenSerialized["project"]["name"] = serialize($token->project->name);
		foreach($token->catalog->services as $service){
			$tokenSerialized["catalog"][serialize($service->id)]["name"] = serialize($service->name);
			$tokenSerialized["catalog"][serialize($service->id)]["description"] = serialize($service->description);
			$tokenSerialized["catalog"][serialize($service->id)]["type"] = serialize($service->type);
			foreach($service->endpoints as $end){
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["interface"] = serialize($end->interface);
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["name"] = serialize($end->name);
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["serviceId"] = serialize($end->serviceId);
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["region"] = serialize($end->region);
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["links"] = serialize($end->links);
				$tokenSerialized["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["url"] = serialize($end->url);
			}
			$tokenSerialized["roles"][serialize($service->id)]["links"] = serialize($service->links);
		}
		$tokenSerialized["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["issued"] = serialize($token->issued);
		$tokenSerialized["id"] = serialize($token->id);		

		return $tokenSerialized;
	}
	
	private function unserializeToken($tokenSerialized){
		$api = new Api();
		$token = new Models\Token($this->httpClient, $api);
		$token->methods = unserialize($tokenSerialized["methods"]);
		$token->roles = [];
		foreach($tokenSerialized["roles"] as $key => $role){
			$tmp = new Models\Role($this->httpClient, $api);
			
			$tmp->name = unserialize($key);
			$tmp->links = unserialize($role["links"]);
			$tmp->id = unserialize($role["id"]);
			
			$token->roles[] = $tmp;
		}
		
		$token->expires = unserialize($tokenSerialized["expires"]);
		$token->project = new Models\Project($this->httpClient, $api);
		$token->project->domainId = unserialize($tokenSerialized["project"]["domainId"]);
		$token->project->parentId = unserialize($tokenSerialized["project"]["parentId"]);
		$token->project->enabled = unserialize($tokenSerialized["project"]["enabled"]);
		$token->project->description = unserialize($tokenSerialized["project"]["description"]);
		$token->project->id = unserialize($tokenSerialized["project"]["id"]);
		$token->project->links = unserialize($tokenSerialized["project"]["links"]);
		$token->project->name = unserialize($tokenSerialized["project"]["name"]);
		
		$token->catalog = [];
		foreach($tokenSerialized["catalog"] as $key => $service){
			$tmp = new Models\Service($this->httpClient, $api);
			
			$tmp->id = unserialize($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 = unserialize($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[] = $tmp;
		}
		
		$token->extras = unserialize($tokenSerialized["extras"]);
		$token->user = new Models\User($this->httpClient, $api);
		$token->user->domainId = unserialize($tokenSerialized["user"]["domainId"]);
		$token->user->defaultProjectId = unserialize($tokenSerialized["user"]["defaultProjectId"]);
		$token->user->id = unserialize($tokenSerialized["user"]["id"]);
		$token->user->email = unserialize($tokenSerialized["user"]["email"]);
		$token->user->enabled = unserialize($tokenSerialized["user"]["enabled"]);
		$token->user->links = unserialize($tokenSerialized["user"]["links"]);
		$token->user->name = unserialize($tokenSerialized["user"]["name"]);
		$token->user->description = unserialize($tokenSerialized["user"]["description"]);
		$token->issued = unserialize($tokenSerialized["issued"]);
		$token->id = unserialize($tokenSerialized["id"]);
	
		return $token;
	}
}