<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;

use ModulesGarden\ProxmoxAddon\App\Events\Vps\QemuUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;

class RestoreVm extends BaseJob
{
    use ProductService;

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