<?php


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


use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

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->initVm();
        $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 (sl('Vm')->getVm()->config() as $k => $v)
            {
                if (preg_match('/cloudinit/', $v))
                {
                    sl('Vm')->getVm()->deleteConfig($k);
                    $delete[$k] = $v;
                }
            }
            $migration = [
                "target" => $this->getModelData()['targetNode'],
                "online" => sl('Vm')->getVm()->isRunning() ? 1 : 0,
            ];
            if($this->configuration()->isLoadBalancerMigrationWithLocalDisks() && $this->configuration()->isQemu()){
                $migration['with-local-disks'] = 1;
            }
            $taskId = sl('Vm')->getVm()->migrate($migration);
            //save task id
            $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode(), "migrate" => true, "config" => ["delete" => $delete]]);
            $this->log->info(sprintf("VM %s - Migrate", sl('Vm')->getVm()->getVmid()));
            //sleep
            $this->sleep(20);
            return false;
        }
        else
        {
            if ($this->isDone())
            {
                $this->customFieldUpdate("node", $this->getModelData()['targetNode']);
                sl('Vm')->getVm()->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];
                        sl('Vm')->getVm()->updateConfig([$k => "{$storage}:cloudinit,format=raw"]);
                        unset($delete[$k]);
                    }
                }
                return true;
            }
            else
            {
                if ($this->isTaskRunning())
                {
                    //sleep
                    $this->sleep(20);
                    return false;
                }
            }
        }
        return true;

    }

}