<?php


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


use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateLxcJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateQemuJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\LoadBalancer\UpgradeVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\MigrateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall\CreateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RestoreVm;
use ModulesGarden\ProxmoxAddon\App\Models\Job;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\Servers\ProxmoxCloudVps\App\Factory\VmModelFactory;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Home\Pages\VmBuild;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\view;


trait BaseClientController
{
    public function isVmCreated(   VmModel $vmModel)
    {
        $jobs = [
            CloneQemuJob::class,
            CreateQemuJob::class,
            CreateLxcJob::class,
            MigrateVmJob::class,
            RestoreVm::class,
            \ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall\RestoreVm::class,
            UpgradeVmJob::class,
            CreateVmJob::class
        ];
        if (!$vmModel->vmid || $vmModel->vmid == 0 ){
            return false;
        }
        if(Job::waiting()->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofJobs($jobs)->ofCustomId($vmModel->id)->count() > 0){
            return false;
        }

        return true;
    }

    /**
     * @return \ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\View|object|null
     * @todo
     */
    public function onVpsBuild()
    {
        return view()->addElement(VmBuild::class);
    }

    protected function initVm(){
        $vmModel =  (new VmModelFactory)->fromRequest();
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVmModel($vmModel);
        if($vmModel->vmid==0){
            return;
        }
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVm((new VmFactory())->fromVmModel($vmModel));
    }
}