<?php


namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;


use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
use ModulesGarden\ProxmoxAddon\App\Factory\Ssh2Factory;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\BaseJob;
use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
use ModulesGarden\ProxmoxAddon\App\Providers\SnippetProvider;
use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
use ModulesGarden\ProxmoxAddon\App\Services\CloudInitScriptConveter;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;

class UpdateSnippet extends CreateSnippet
{
    use ProductService;

    public function handle($text)
    {
        $this->initParams();
        $this->initServices();
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        //Get cloud init script
        if($this->isWhmcsConfigOption(ConfigurableOption::CLOUD_INIT_SCRIPT) &&
            $this->getWhmcsConfigOption(ConfigurableOption::CLOUD_INIT_SCRIPT) !=0 ){
            $id =  $this->getWhmcsConfigOption(ConfigurableOption::CLOUD_INIT_SCRIPT);
        }else{
            $id = $this->configuration()->getCloudInitScript();
        }
        $serverConfiguration = new ServerConfigurationRepository($this->getWhmcsParamByKey('serverid'));
        $ssh = (new Ssh2Factory())->fromServerConfiguration( $serverConfiguration);
        $cloudInitScript = CloudInitScript::findOrFail($id);
        $conveter = new CloudInitScriptConveter($cloudInitScript, $serverConfiguration);
        $snippetProvider = new SnippetProvider($ssh);
        $this->params['password'] = decrypt($this->getModelData()['password']);
        foreach ($conveter->convert() as  $snippet ){
            $snippetProvider->update($snippet);
        }

    }
}