<?php

namespace ModulesGarden\Servers\ProxmoxVps\App\Http\Client;

use MGProvision\Proxmox\v2\Api;
use ModulesGarden\ProxmoxAddon\App\Models\ModuleSettings;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UserService;
use ModulesGarden\Servers\ProxmoxVps\App\Helpers\AppParams;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Home\Pages\DetailsContainer;
use ModulesGarden\Servers\ProxmoxVps\Core\Http\AbstractClientController;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Traits\WhmcsParams;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class Console extends AbstractClientController
{

    use WhmcsParams;
    use UserService;
    use ApiService;
    use ProductService;


    public function novnc()
    {
        (new AppParams())->initFromWhmcsParams();
        $this->acl()->novnc();
        $this->console(['novnc' => 1]);
    }

    public function xtermjs()
    {
        (new AppParams())->initFromWhmcsParams();
        $this->acl()->xtermjs();
        $this->console(['xtermjs' => 1]);
    }

    private function console($request = [])
    {
        $serverHost = $this->getWhmcsParamByKey('serverip') ? $this->getWhmcsParamByKey('serverip') : $this->getWhmcsParamByKey('serverhostname');
        //Host
        $consoleHost = $this->getWhmcsParamByKey('serverhostname') ? $this->getWhmcsParamByKey('serverhostname') : $this->getWhmcsParamByKey('serverip');
        if ($this->configuration()->getConsoleHost())
        {
            $consoleHost = $this->configuration()->getConsoleHost();
        }
        //Port
        $consolePort = 8006;
        if(is_numeric($this->getWhmcsParamByKey('serverport'))){
            $consolePort = $this->getWhmcsParamByKey('serverport');
        }
        if (preg_match('/\:/', $consoleHost))
        {
            $ex          = explode(":", $consoleHost);
            $consoleHost = $ex['0'];
            $consolePort = $ex['1'];
        }
        try
        {
            //User
            $vpsUser = $this->getUser();
            if (empty($vpsUser->username))
            {
                throw new \Exception('User does not have permissions to access noVNC console');
            }
            //Load Users API
            if(!preg_match('/\:/', $serverHost) && $this->getWhmcsParamByKey('serverport') ){
                $serverHost .=":".$this->getWhmcsParamByKey('serverport');
            }
            $api = new Api($serverHost, $vpsUser->username, $vpsUser->realm, $vpsUser->getPassword());
            $api->debug(ModuleSettings::isDebug());
            //User Authorization
            $ticket                         = $api->getLoginTicket();
            $request['token']               = $ticket['ticket'];
            $request['CSRFPreventionToken'] = $ticket['CSRFPreventionToken'];
            $request['console']             = $this->vm()->getVirtualization();
            /* @deprecated $vars['virtualization'] since version 2.6.0 */
            $request['virtualization'] = $this->vm()->getVirtualization();
            $request['node']           = $this->vm()->getNode();
            $request['vmid']           = $this->vm()->getVmid();
        }
        catch (\Exception $ex)
        {

            $request['error'] = $ex->getMessage();
        }
        $response = new RedirectResponse("https://{$consoleHost}:{$consolePort}/novnc/mgnovnc.html?" . http_build_query($request));
        $response->send();
    }

    public function spice()
    {
        (new AppParams())->initFromWhmcsParams();
        $this->acl()->spice();
        $proxy       = $this->vm()->spiceproxy();
        $consoleHost = $this->getWhmcsParamByKey('serverhostname') ? $this->getWhmcsParamByKey('serverhostname') : $this->getWhmcsParamByKey('serverip');
        if ($this->configuration()->getConsoleHost())
        {
            $consoleHost = $this->configuration()->getConsoleHost();
        }
        if ($consoleHost)
        {
            $ex             = explode(":", $proxy['proxy']);
            $port           = end($ex);
            $proxy['proxy'] = "http://{$consoleHost}:{$port}";
        }
        $content = "[virt-viewer]\r\n";
        foreach ($proxy as $k => $v)
        {
            $content .= "{$k}={$v}\r\n";
        }
        //Response
        $response = new StreamedResponse();
        $response->setStatusCode(200);
        $response->headers->set('Cache-Control', 'public');
        $response->headers->set('Content-Type', 'application/x-virt-viewer');
        $response->headers->set('Content-Transfer-Encoding', 'Binary');
        $response->setCallback(function () use ($content)
        {
            echo $content;
            die();
        });
        $fileName = Utility::generatePassword(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        $fileName .= ".vv";
        $response->headers->set(
            'Content-Disposition', "attachment; filename=\"{$fileName}\""
        );
        $response->send();
        exit();
    }
}
