<?php


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


use MGProvision\Proxmox\v2\repository\FileRepository;
use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class RestoreVm extends BaseJob
{
    use ProductService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->initVm();
        if ($this->isTaskRunning())
        {
            $this->sleep(20);
            return false;
        }
        //get backup
        $storage        = $this->configuration()->getBackupStorage() ? $this->configuration()->getBackupStorage() : 'local';
        $fileRepository = new FileRepository();
        $fileRepository->findBackup(sl('Vm')->getVm())
            ->findByStorages([$storage]);
        $backup = $fileRepository->fetchLast();
        //done process is finished
        if ($this->isDone())
        {
            $backup->delete();
            return true;
        }
        //restore
        $taskId = sl('Vm')->getVm()->restore($backup->getVolid());
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode()]);
        $this->sleep(20);
        return false;
    }

}