<?php


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


use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\Lxc;
use ModulesGarden\ProxmoxAddon\App\Factory\ProxyServiceFactory;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\CloneQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\CreateLxcJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\CreateQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\LoadBalancer\UpgradeVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\MigrateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\Reinstall\CreateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\RestoreVm;
use ModulesGarden\ProxmoxAddon\App\Models\Job;
use ModulesGarden\ProxmoxAddon\App\Models\ModuleSettings;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Home\Pages\VpsBuild;
use ModulesGarden\Servers\ProxmoxVps\Core\ModuleConstants;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\sl;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\view;

/**
 * Trait BaseClientController
 * @method Kvm|Lxc vm()
 */
trait BaseClientController
{
    public function isVpsCreated()
    {
        $jobs = [
            CloneQemuJob::class,
            CreateQemuJob::class,
            CreateLxcJob::class,
            MigrateVmJob::class,
            RestoreVm::class,
            \ModulesGarden\ProxmoxAddon\App\Jobs\Vps\Reinstall\RestoreVm::class,
            UpgradeVmJob::class,
            CreateVmJob::class
        ];
        if(Job::waiting()->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofJobs($jobs)->count() > 0){
            return false;
        }else if (!$this->getWhmcsCustomField("vmid")){
            return false;
        }
        return true;
    }

    public function onVpsBuild()
    {
        return view()->addElement(VpsBuild::class);
    }

    /**
     * @return Kvm|Lxc
     */
    protected function vmAsUser(){
        if($this->vmAsUser){
            return $this->vmAsUser;
        }
        //User
        $vpsUser = $this->getUser();
        if (empty($vpsUser->username))
        {
            throw new \Exception('User does not have permissions to access noVNC console');
        }
        $serverHost = $this->getWhmcsParamByKey('serverip') ? $this->getWhmcsParamByKey('serverip') : $this->getWhmcsParamByKey('serverhostname');
        //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());
        //vm
        $vm = $this->vm();
        $vm->setApi($api);
        if(!$vm->isRunning()){
            throw new \Exception(sl('lang')->abtr("VM not running"));
        }
        return $this->vmUser = $vm;
    }

    public function novncProxy(){
        $vars=[
            'novncAppUrl' => './modules/addons/proxmoxAddon/templates/client/default/novnc'
        ];
        if($this->isAdmin()){
            $vars['novncAppUrl']=  '../modules/addons/proxmoxAddon/templates/client/default/novnc';
        }
        try{
            $vnc = $this->vmAsUser()->vncproxy(1);
            $vncHost = $this->vmAsUser()->vncWebsocketPath( $vnc);
            $clientIp = sl('request')->getClientIp();
            //proxy generate token
            $procyService = (new ProxyServiceFactory())->fromModuleConfiguration($this->moduleSetting);
            $vars['websocketUrl'] = $procyService->proxmox("https://".$vncHost, $clientIp ,$this->vmAsUser()->getApi()->getAuthCookieAsArray());
            $vars['password'] = $vnc['ticket'];
        }catch (\Exception $ex){
            $vars['error'] = $ex->getMessage();
        }
        echo $this->getSmarty()
            ->view(ModuleConstants::getFullPathWhmcs().DS.'modules'.DS.'addons'.DS.'proxmoxAddon'.DS.'templates'.DS.'client'.DS.'default'.DS.'pages'.DS.'console'.DS.'novnc', $vars);
        exit();
    }

    public function xtermjsProxy(){

        $vars=[
            'appUrl' => './modules/addons/proxmoxAddon/templates/client/default',
        ];
        if($this->isAdmin()){
            $vars['appUrl']=  '../modules/addons/proxmoxAddon/templates/client/default';
        }
        try{
            $vnc = $this->vmAsUser()->termproxy();
            $vncHost = $this->vmAsUser()->vncWebsocketPath( $vnc);
            $clientIp = sl('request')->getClientIp();
            //proxy generate token
            $procyService = (new ProxyServiceFactory())->fromModuleConfiguration($this->moduleSetting);
            $vars['websocketUrl'] = $procyService->proxmox("https://".$vncHost,$clientIp, $this->vmAsUser()->getApi()->getAuthCookieAsArray());
            $vars['password'] = $vnc['ticket'];
            $vars['user'] =$vnc['user'];
        }catch (\Exception $ex){
            $vars['error'] = $ex->getMessage();
        }
        echo $this->getSmarty()
            ->view(ModuleConstants::getFullPathWhmcs().DS.'modules'.DS.'addons'.DS.'proxmoxAddon'.DS.'templates'.DS.'client'.DS.'default'.DS.'pages'.DS.'console'.DS.'xtermjs', $vars);
        exit();
    }
}