<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\LoadBalancer;

use ModulesGarden\ProxmoxAddon\App\Events\Cloud\LxcUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\QemuUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\IpSetIpFilterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;

class UpgradeVmJob extends BaseJob
{
    use ProductService;
    /**
     * @var  HighAvailabilityClusterService
     */
    protected $highAvailabilityClusterService;
    protected $ipSetIpFilterService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->initVm();
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        $this->ipSetIpFilterService           = new IpSetIpFilterService();
        //Upgrade
        if ($this->configuration()->isQemu())
        {
            $evnet = new QemuUpdateEvent($this->getVmModel());
            $evnet->isChangeVmPassword(false);
            fire($evnet);
        }
        elseif ($this->configuration()->isLxc())
        {
            fire(new LxcUpdateEvent($this->getVmModel()));
        }
        //createHaResource
        if ($this->highAvailabilityClusterService->isConfigured()  )
        {
            $this->highAvailabilityClusterService->create();
        }
        //ip set filter
        if ($this->configuration()->isIpsetIpFilter())
        {
            $this->ipSetIpFilterService->create();
        }
        //start vm
        if (!sl('Vm')->getVm()->isRunning())
        {
            sl('Vm')->getVm()->start();
        }

    }

}