<?php


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


use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\BaseJob;
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()))
        {
            $this->highAvailabilityClusterService->delete();
            $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'],
                "online" => $this->vm()->isRunning() ? 1 : 0,
            ];
            if($this->configuration()->isLoadBalancerMigrationWithLocalDisks() && $this->configuration()->isQemu()){
                $migration['with-local-disks'] = 1;
            }
            $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(20);
            return false;
        }
        else
        {
            if ($this->isDone())
            {
                $this->customFieldUpdate("node", $this->getModelData()['targetNode']);
                $this->vm()->setNode($this->getModelData()['targetNode']);
                $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]);
                    }
                }
                return true;
            }
            else
            {
                if ($this->isTaskRunning())
                {
                    //sleep
                    $this->sleep(20);
                    return false;
                }
            }
        }
        return true;

    }

}