<?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 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->backup['Identity'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );
		
		$this->optionsGlobal['Identity'] = $options;
	}
	
	public function loadIdentityBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'false';
		$options['catalogType'] = 'false';
		$options['region'] = 'RegionOne';
		
		$this->backup['Identity'] = unserialize($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->backup['Identity'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );		
		$this->optionsGlobal['Identity'] = $options;
		
	}
	
	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->backup['Image'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );
		
		$this->optionsGlobal['Image'] = $options;
	}
	
	public function loadImageBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'glance';
		$options['catalogType'] = 'image';
		$options['region'] = 'RegionOne';
		
		$this->backup['Image'] = unserialize($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->backup['Image'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );		
		$this->optionsGlobal['Image'] = $options;
	}
	
	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->backup['Network'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );
		
		$this->optionsGlobal['Network'] = $options;
	}
	
	public function loadNetworkBackup($opt){
		$options = $this->optionsGlobal['Common'];
		$options['catalogName'] = 'neutron';
		$options['catalogType'] = 'network';
		$options['region'] = 'RegionOne';
		
		$this->backup['Network'] = unserialize($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->backup['Network'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );		
		$this->optionsGlobal['Network'] = $options;
	}
	
	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->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';
		
		$this->backup['Compute'] = unserialize($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->backup['Compute'] = array('token' => $this->serializeToken($token), 'baseUrl' => $baseUrl );		
		$this->optionsGlobal['Compute'] = $options;
	}

	public function getBackup($service){
		return serialize($this->backup[$service]);
	}
	
	public function getOptions($service){
		return $this->optionsGlobal[$service];
	}
	
	private function serializeToken($token){
		$tokenSerialized = [];
		$tokenSerialized["methods"] = serialize($token->methods);
		$tokenSerialized["roles"] = [];

		foreach($token->roles as $role){
			$tokenSerialized["roles"][serialize($role->id)]["links"] = serialize($role->links);
			$tokenSerialized["roles"][serialize($role->id)]["name"] = serialize($role->name);
		}

		$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->id = unserialize($key);
			$tmp->links = unserialize($role["links"]);
			if(isset($role["name"]))
				$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($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 = new Models\Catalog($this->httpClient, $api);
		$token->catalog->services = [];
		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;
			}
			if(isset($service["links"]))
				$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($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;
	}
}
