<?php
namespace ModulesGarden\ProxmoxAddon\App\Providers;

use ModulesGarden\ProxmoxAddon\App\Models\Snippet;
use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
use phpseclib3\Net\SSH2;

class SnippetProvider
{
    /**
     * @var SSH2
     */
    protected $ssh;
    protected $lastResponse;


    /**
     * SnippetProvider constructor.
     * @param SSH2 $ssh
     * @param ServerConfigurationRepository $cerverConfiguration
     */
    public function __construct(SSH2 $ssh)
    {
        $this->ssh = $ssh;
    }

    public function create(Snippet $snippet){
        if($this->exists($snippet)){
            throw new \Exception(sprintf("File already exist: %s",$snippet->getFileDirectory()));
        }
        $this->lastResponse = $this->ssh->exec(sprintf("echo '%s' > %s", $snippet->getContent(), $snippet->getFileDirectory()));
    }

    /**
     * @param Snippet $snippet
     * @return bool
     * @example ls /var/lib/vz/snippets/userconfig.yaml
     */
    public function exists(Snippet $snippet){
        $this->lastResponse = $this->ssh->exec(sprintf("ls %s", $snippet->getFileDirectory()) );
        $response = str_replace(["\r", "\n"],["",""],$this->lastResponse );
        return $response == $snippet->getFileDirectory() ;
    }

    public function delete(Snippet $snippet){
        $this->lastResponse = $this->ssh->exec(sprintf("rm %s", $snippet->getFileDirectory()) );
        if(preg_match("/cannot remove/",$this->lastResponse)){
            throw new \Exception($this->lastResponse);
        }
    }

    public function update(Snippet $snippet){
        $this->lastResponse = $this->ssh->exec(sprintf("echo '%s' > %s", $snippet->getContent(), $snippet->getFileDirectory()));
    }
}