<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;


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

class RebootVmJob extends BaseJob
{
    use ProductService;

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        $this->api();
        $this->initVm();
        //shutdown
        if (!$this->getModelData()['shutdown'] && sl('Vm')->getVm()->isRunning())
        {
            $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();
            return false;
        }
        else
        {
            if ($this->getModelData()['shutdown'])
            {
                //start
                if ($this->isDone() && !sl('Vm')->getVm()->isRunning())
                {
                    sl('Vm')->getVm()->start();
                    $this->log->info(sprintf("VM %s - Start", sl('Vm')->getVm()->getVmid()));
                    return true;
                    //in progress
                }
                else
                {
                    if ($this->getTask()->isRunning())
                    {
                        $this->log->info(sprintf("VM %s - Waiting for Shutdown ", sl('Vm')->getVm()->getVmid()));
                        $this->sleep(5);
                        return false;
                    }
                    else
                    {
                        $this->putModelDataAndSave(["shutdown" => false]);
                        //sleep
                        $this->sleep();
                        return false;
                    }
                }
            }
        }
    }

}