<?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\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class ShutdownVmJob extends BaseJob
{
    use ProductService;
    /**
     * @var  HighAvailabilityClusterService
     */
    protected $highAvailabilityClusterService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        $this->initVm();
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        //shutdown
        if (!$this->getModelData()['shutdown'] && sl('Vm')->getVm()->isRunning())
        {
            $this->highAvailabilityClusterService->delete();
            $taskId = sl('Vm')->getVm()->shutdown();
            //save task id
            $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode(), "shutdown" => true]);
            $this->log->info(sprintf("VM %s - Shutdown", sl('Vm')->getVm()->getVmid()));
            //sleep
            $this->sleep(20);
            return false;
        }
        else
        {
            if ($this->getModelData()['shutdown'])
            {
                //start
                if ($this->isDone() && !sl('Vm')->getVm()->isRunning())
                {
                    return true;
                }
                else
                {
                    if ($this->getTask()->getStatus() == "running")
                    {
                        //sleep
                        $this->sleep(20);
                        return false;
                    }
                    else
                    {
                        if ($this->getTask()->isFalied() && $this->configuration()->isLoadBalancerStopOnUpgrade())
                        {
                            $taskId = sl('Vm')->getVm()->stop();
                            $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode(), "shutdown" => true]);
                            $this->log->info(sprintf("VM %s - Stop", sl('Vm')->getVm()->getVmid()));
                            $this->sleep(20);
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

}