<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;


use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;

class RebootVmJob extends BaseJob
{
    use ProductService;

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

        }
    }

}