<?php


namespace ModulesGarden\ProxmoxAddon\App\Services;


class ProxyService{

    protected $apiKey;
    protected $consoleHost;
    protected $restFullApi;
    const TOKEN_CREATE = 'token';
    const TOKEN_PROXMOX = 'proxmox';
    const AUTH ='auth';

    public function  __construct($apiKey, $consoleHost, RestFullApi $restFullApi)
    {
        if(!$apiKey){
            throw  new \InvalidArgumentException("Parameter verification failed, API Key is empty");
        }
        if(!$consoleHost){
            throw  new \InvalidArgumentException("Parameter verification failed, Console Host is empty");
        }
        $this->apiKey = $apiKey;
        $this->consoleHost = $consoleHost;

        $this->restFullApi = $restFullApi;
    }

    public function token($url,$ip, $cookie=[], $get=[], $post=[]){
        $request = http_build_query([
            'securityToken' => $this->apiKey,
            'URL'           => $url,
            'GET'           => $get,
            'COOKIE'        => $cookie,
            'POST'          => $post,
            'ip' =>  $ip
        ]);
        return $this->restFullApi->post("/".ProxyService::TOKEN_CREATE, $request);
    }

    public function proxmox($url, $clientIpAddres, $cookie){
        if(!$url){
            throw  new \InvalidArgumentException("noVNC URL is empty");
        }
        if(!$cookie['PVEAuthCookie']){
            throw  new \InvalidArgumentException("Auth Cookie is empty");
        }
        $response = $this->token($url, $clientIpAddres, $cookie);
        if(!$response['token']){
            throw  new \InvalidArgumentException("Parameter verification failed, API Key is invalid.");
        }
        $host = $this->consoleHost;
        if(preg_match("/http/", $this->consoleHost)){
            $host = str_replace(["http://", "https://"],["",""],$this->consoleHost);
        }
        //ws://10.10.10.12/Cvz8PpbSmmqQOmrbQ8Q9GvS3PRXxdWdd/proxmox
        return sprintf("wss://%s/%s/%s/%s",$host, ProxyService::AUTH ,$response['token'],ProxyService::TOKEN_PROXMOX);
    }




}