<?php
namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;

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

class CreateSnippet extends BaseJob
{
    use ProductService;

    public function handle($text)
    {
        $this->initParams();
        $this->initServices();
        //Get cloud init script
        $id = $this->getModelData()['cloudInitScript'];
        $serverConfiguration = new ServerConfigurationRepository($this->getWhmcsParamByKey('serverid'));
        $ssh = (new Ssh2Factory())->fromServerConfiguration( $serverConfiguration);
        $cloudInitScript = CloudInitScript::findOrFail($id);
        $vmModel =  $this->getVmModel();
        $vmModel->ciuser = $this->getModelData()['ciuser'];
        $vmModel->sshkeys = $this->getModelData()['sshkeys'];
        $conveter = new CloudInitScriptConveter($cloudInitScript, $serverConfiguration, $vmModel);
        $snippetProvider = new SnippetProvider($ssh);
        foreach ($conveter->convert() as  $snippet ){
            $snippetProvider->create($snippet);
        }
    }
}