<?php


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


use MGProvision\Proxmox\v2\repository\FileRepository;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;

class RestoreVm extends BaseJob
{
    use ProductService;

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

}