<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;

use MGProvision\Proxmox\v2\models\Kvm;
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->initVm();
        $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 (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'],
            ];
            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 = 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(5);
            return false;
        } else if ($this->isDone()) {
            $this->getVmModel()->node =  $this->getModelData()['targetNode'];
            $this->getVmModel()->save();
            sl('Vm')->getVm()->setNode($this->getModelData()['targetNode']);
            //restore config
            if(sl('Vm')->getVm() instanceof  Kvm && !sl('Vm')->getVm()->hasCloudInit()){
                $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]);
                    }
                }
            }
            if ($this->highAvailabilityClusterService->isConfigured()) {
                $this->highAvailabilityClusterService->create();
            }
            return true;
        } else if ($this->isTaskRunning()) {
            //sleep
            $this->sleep(5);
            return false;

        }
    }
}