<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;


use Illuminate\Database\Capsule\Manager as DB;
use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\Node;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\CustomField;
use ModulesGarden\ProxmoxAddon\App\Events\Vps\VmCreatedEvent;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UserService;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;

class RestoreArchiveJob  extends CloneQemuJob
{

    public function handle()
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        if ($this->isDone()) {
            $this->qemuUpdate();
            if ($this->agentUpdate()) {
                fire(new VmCreatedEvent($this->vm()));
                return true;
            }
            return false;
        }elseif ($this->isTaskRunning())
        {
            //sleep
            $this->sleep(5);
            return false;
        }
        try {
            Api::beginTransaction();
            DB::beginTransaction();
            if($this->isWhmcsConfigOption(ConfigurableOption::ARCHIVE) && $this->getWhmcsConfigOption(ConfigurableOption::ARCHIVE) !="0"){
                $archive = $this->getWhmcsConfigOption(ConfigurableOption::ARCHIVE);
            }else{
                $archive = $this->configuration()->archive;
            }
            list($backupNode, $volid) = explode(":", $archive, 2);
            //vmid
            $vmid = $this->nextVmid();
            $this->customFieldUpdate("vmid", $vmid);
            $vm          = new Kvm($backupNode,$vmid);
            $vm->setApi($this->api());
            $container = [
                'vmid'   => $vmid,
                'archive' => $volid
            ];
            $this->setVm($vm);
            $taskId = $vm->create($container);
            $this->customFieldUpdate("node", $backupNode);
            DB::commit();
        }catch (\Exception $ex)
        {
            echo $ex->getMessage();
            DB::rollBack();
            Api::commit();
            throw $ex;
        }
        //task history
        $this->createTaskHistory($taskId, "Create");
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $backupNode]);
        //sleep
        $this->sleep();
        return false;

    }
}