<?php


namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Home\Pages;


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\Models\Job;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Builder\BaseContainer;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AdminArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

/**
 * Class VmBuild
 * @package ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Home\Pages
 * @todo
 */
class VmBuild extends BaseContainer implements ClientArea, AdminArea
{

    public function initContent()
    {
        if ($this->isVmCreate())
        {
            $this->customTplVars['warning'] = sl("lang")->abtr('The process of Virtual Machine creation is in progress.');
        }
        else if ($this->isVmReinstall()) {
                $this->customTplVars['warning'] = sl("lang")->abtr('Rebuild VM in progress. Please try again later.');
        } else if ($this->isVmUpgrade()){
            $this->customTplVars['warning'] = sl("lang")->abtr('Upgrading VM in progress. Please try again later.');
        }else {
            $this->customTplVars['warning'] = sl("lang")->abtr('Unknown error.');
        }
    }

    private function isVmCreate()
    {
        $jobs = [
            CloneQemuJob::class,
            CreateQemuJob::class,
            CreateLxcJob::class,
        ];
        return Job::waiting()->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofJobs($jobs)->count();
    }

    private function isVmReinstall()
    {
        $jobs = [
            CreateVmJob::class
        ];
        return Job::waiting()->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofJobs($jobs)->count();
    }

    private function isVmUpgrade()
    {
        $jobs = [
            MigrateVmJob::class,
            \ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RestoreVm::class,
            UpgradeVmJob::class
        ];
        return Job::waiting()->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofJobs($jobs)->count();
    }
}