<?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->saveBackup('Identity', array('token' => $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'] = $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;
		
	}
	
	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;
	}
	
	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;
	}
	
	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;
	}
	
	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;
	}
	
	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;
	}
	
	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;
	}

	private function saveBackup($name, $data){
		$token = $this->serializeToken($data["token"]);
		$path = "core/LibOverride/projectTokenData/".$token['saved']["project"]["name"];
		error_log(print_r($path, true), 0);
		file_put_contents("core/LibOverride/projectTokenData/".$token['saved']["project"]["name"], serialize($token['saved']));
		$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"] );
	}
	
	public function getBackup(){
		return serialize($this->backup);
	}
	
	public function loadBackup($back){
		
		$backup = unserialize($back);

		$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"]);
		
	}
	
	public function getOptions($service){
		return $this->optionsGlobal[$service];
	}
	
	private function serializeToken($token){
		$tokenSerialized = [];
		$tokenSerialized["token"]["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["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;
		
		foreach($token->catalog->services as $service){
			$tokenSerialized['saved']["catalog"][serialize($service->id)]["name"] = serialize($service->name);
			$tokenSerialized['saved']["catalog"][serialize($service->id)]["description"] = serialize($service->description);
			$tokenSerialized['saved']["catalog"][serialize($service->id)]["type"] = serialize($service->type);
			foreach($service->endpoints as $end){
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["interface"] = serialize($end->interface);
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["name"] = serialize($end->name);
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["serviceId"] = serialize($end->serviceId);
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["region"] = serialize($end->region);
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["links"] = serialize($end->links);
				$tokenSerialized['saved']["catalog"][serialize($service->id)]["endpoints"][serialize($end->id)]["url"] = serialize($end->url);
			}
			$tokenSerialized['saved']["catalog"][serialize($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);		

		return $tokenSerialized;
	}
	
	private function unserializeToken($tokenSerialized){
		$Saved = file_get_contents("core/LibOverride/projectTokenData/".$this->backup["project"]);
		$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 = unserialize($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 = 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->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;
	}
}