<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Agent;


use MGProvision\Proxmox\v2\ProxmoxApiException;
use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class ChangePasswordJob extends BaseJob
{
    use ProductService;

    protected function initServices()
    {
        $this->agentService = new AgentService();
    }

    public function handle($text = null)
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        $this->initVm();
        $this->api();
        try{
            if(!sl('Vm')->getVm()->isRunning()){
                $this->log->info(sprintf("VM %s - Start", sl('Vm')->getVm()->getVmid()));
                sl('Vm')->getVm()->start();
                $this->sleep(40);
                return false;
            }
            sl('Vm')->getVm()->agent()->ping();
            $this->agentService->passwordUpdate();

        }catch (ProxmoxApiException $ex){
            if(preg_match("/not running/", $ex->getMessage())){
                $this->log->info($ex->getMessage());
            }else{
                $this->log->error($ex->getMessage());
            }
            //sleep
            $this->sleep(30);
            return false;
        }
    }

}