<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;

use MGProvision\Proxmox\v2\models\Kvm;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;

class MigrateVmJob extends BaseJob
{
    use ProductService;
    use HostingService;

    /**
     * @var  HighAvailabilityClusterService
     */
    protected $highAvailabilityClusterService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        //Migrate
        if (!$this->getModelData()['taskId'] || ($this->isTask()  && !$this->isTaskRunning() && $this->isFailed())) {
            if($this->isTask() && $this->isFailed()){
                $this->log->error(ucfirst($this->getTask()->getExitstatus()));
            }
            $this->highAvailabilityClusterService->delete();
            //delete config
            $delete = (array)$this->getModelData()['config']['delete'];
            foreach ($this->vm()->config() as $k => $v) {
                if (preg_match('/cloudinit/', $v)) {
                    $this->vm()->deleteConfig($k);
                    $delete[$k] = $v;
                }
            }
            $migration = [
                "target" => $this->getModelData()['targetNode'],
            ];
            if($this->configuration()->isLxc() && is_numeric($this->getModelData()['restart'])){
                $migration['restart'] = $this->getModelData()['restart'];
            }
            if($this->configuration()->isQemu()){
                $migration['online'] = $this->getModelData()['online'];
                $migration['with-local-disks'] = $this->getModelData()['with-local-disks'];
            }
            $taskId = $this->vm()->migrate($migration);
            //save task id
            $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->vm()->getNode(), "migrate" => true, "config" => ["delete" => $delete]]);
            $this->log->info(sprintf("VM %s - Migrate", $this->vm()->getVmid()));
            //sleep
            $this->sleep(5);
            return false;
        } else if ($this->isDone()) {
            $this->customFieldUpdate("node", $this->getModelData()['targetNode']);
            $this->vm()->setNode($this->getModelData()['targetNode']);
            //restore config
            if($this->vm() instanceof  Kvm && !$this->vm()->hasCloudInit()){
                $delete = (array)$this->getModelData()['config']['delete'];
                foreach ($delete as $k => $v) {
                    if (preg_match('/cloudinit/', $v)) {
                        $ex = explode(":", $v);
                        $storage = $ex[0];
                        $this->vm()->updateConfig([$k => "{$storage}:cloudinit,format=raw"]);
                        unset($delete[$k]);
                    }
                }
            }
            if ($this->highAvailabilityClusterService->isConfigured()) {
                $this->highAvailabilityClusterService->create();
            }
            return true;
        } else if ($this->isTaskRunning()) {
            //sleep
            $this->sleep(5);
            return false;

        }
    }
}