<?php

namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;

use Illuminate\Database\Capsule\Manager as DB;
use MGProvision\Proxmox\v2\Api;
use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\Lxc;
use MGProvision\Proxmox\v2\ProxmoxApiException;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\QemuUpdateEvent;
use ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmCreatedEvent;
use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Models\TaskHistory;
use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalDiskService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ContainerService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\UserService;
use ModulesGarden\ProxmoxAddon\App\Services\EmailService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class RestoreArchiveJob extends CloneQemuJob
{

    public function handle()
    {
        $this->initParams();
        $this->initServices();
        //create task validation
        if ($this->isDone())
        {
            $this->initVm();
            $this->qemuUpdate();
            if ($this->agentUpdate()) {
                fire(new VmCreatedEvent($this->getVmModel()));
                return true;
            }
            return false;
        }
        elseif ($this->isTaskRunning())
        {
            //sleep
            $this->sleep(5);
            return false;
        }
        try
        {
            Api::beginTransaction();
            DB::beginTransaction();
            list($backupNode, $volid) = explode(":",  $this->getModelData()['archive'], 2);
            //vmid
            $vmid = $this->nextVmid();
            $vm          = new Kvm($backupNode,$vmid);
            $vmModel =    $this->getVmModel();
            $vmModel->vmid = $vmid;
            $vmModel->node = $backupNode;
            $vmModel->save();
            sl('Vm')->setVm(null);
            sl('Vm')->setVmModel( $vmModel);
            $vm->setApi($this->api());
            $container = [
                'vmid'   => $vmid,
                'archive' => $volid
            ];
            $taskId = $vm->create($container);
            DB::commit();
        }
        catch (\Exception $ex)
        {
            DB::rollBack();
            Api::commit();
            $this->failed($ex->getMessage());
            throw $ex;
        }
        //task history
        $this->createTaskHistory($taskId, "Create");
        //save task id
        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $backupNode]);
        //sleep
        $this->sleep();
        return false;
    }


}
