<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;

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

class RestoreVm extends BaseJob
{
    use ProductService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->api();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        $this->initVm();
        if ($this->isDone())
        {
            if ($this->configuration()->isQemu())
            {
                fire(new QemuUpdateEvent($this->getVmModel()));
            }
            if (sl('Vm')->getVm()->isRunning())
            {
                sl('Vm')->getVm()->start();
            }
            return true;
        }
        elseif ($this->isTaskRunning())
        {
            //sleep
            $this->sleep(5);
            return false;
        }
        $taskId = sl('Vm')->getVm()->restore($this->getModelData()['volid']);
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode()]);
        //sleep
        $this->sleep(5);
        return false;
    }
}