<?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\ProductService;

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->highAvailabilityClusterService = new HighAvailabilityClusterService();
        //shutdown
        if (!$this->getModelData()['shutdown'] && $this->vm()->isRunning())
        {
            $this->highAvailabilityClusterService->delete();
            $taskId = $this->vm()->shutdown();
            //save task id
            $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->vm()->getNode(), "shutdown" => true]);
            $this->log->info(sprintf("VM %s - Shutdown", $this->vm()->getVmid()));
            //sleep
            $this->sleep(20);
            return false;
        }
        else
        {
            if ($this->getModelData()['shutdown'])
            {
                //start
                if ($this->isDone() && !$this->vm()->isRunning())
                {
                    return true;
                }
                else
                {
                    if ($this->getTask()->getStatus() == "running")
                    {
                        //sleep
                        $this->sleep(20);
                        return false;
                    }
                    else
                    {
                        if ($this->getTask()->isFalied() && $this->configuration()->isLoadBalancerStopOnUpgrade())
                        {
                            $taskId = $this->vm()->stop();
                            $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->vm()->getNode(), "shutdown" => true]);
                            $this->log->info(sprintf("VM %s - Stop", $this->vm()->getVmid()));
                            $this->sleep(20);
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

}