<?php

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

use MGProvision\Proxmox\v2\models\Kvm;
use ModulesGarden\ProxmoxAddon\App\Models\ModuleSettings;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Admin\IpSet\Pages\IpSetDataTable;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Admin\QemuGuestAgent\Pages\NetworkInterfacesDataTable;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Admin\User\Pages\UserDataTable;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Graph\Pages\CpuGraph;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Graph\Pages\DiskGraph;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Graph\Pages\MemoryGraph;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Graph\Pages\NetworkGraph;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Home\Pages\ServiceActions;
use ModulesGarden\Servers\ProxmoxVps\App\UI\IpAddress\Pages\IpAddressDataTable;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Reinstall\Pages\ReinstallTab;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Reinstall\Pages\TemplateDataTable;
use ModulesGarden\Servers\ProxmoxVps\App\UI\ServiceInformation\Pages\ServiceInformation;
use ModulesGarden\Servers\ProxmoxVps\Core\Helper;
use ModulesGarden\Servers\ProxmoxVps\Core\Http\AbstractController;
use ModulesGarden\Servers\ProxmoxVps\Core\Traits\OutputBuffer;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Traits\WhmcsParams;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UserService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use MGProvision\Proxmox\v2\Api;
/**
 * Example admin home page controler
 * @author Sławomir Miśkowicz <slawomir@modulesgarden.com>
 */
class Home extends AbstractController
{
    use WhmcsParams;
    use ProductService;
    use ApiService;
    use OutputBuffer;
    use UserService;
    public function index()
    {
        $view = Helper\viewIntegrationAddon();
        $view->initCustomAssetFiles();
        //serviceActions
        $view->addElement(ServiceActions::class);
        // serviceInformationDataTable
        $view->addElement(ServiceInformation::class);
        $view->addElement(IpAddressDataTable::class);
        $view->addElement(IpSetDataTable::class);
        if ($this->vm() instanceof Kvm) {

            if ($this->vm()->config()['agent'] == 1) {
                try {
                    $this->vm()->agent()->getHostname();
                    $view->addElement(NetworkInterfacesDataTable::class);
                } catch (\Exception $ex) {

                }
            }
            $view->addElement(ReinstallTab::class);
        } else {
            $view->addElement(TemplateDataTable::class);
        }
        $view->addElement(CpuGraph::class)
            ->addElement(MemoryGraph::class)
            ->addElement(NetworkGraph::class)
            ->addElement(DiskGraph::class)
            ->addElement(UserDataTable::class);
        return $view;

    }

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

    public function xtermjs()
    {
        $this->cleanOutputBuffer();
        $this->acl()->novnc();
        $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();
    }
}
