<?php
namespace ModulesGarden\ProxmoxAddon\App\Traits\Vps;

use MGProvision\Proxmox\v2\repository\FileRepository;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\CustomField;
use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;

trait SnippetTrait
{

    public function hasSnippet(){
        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();
        }
        if(!$id || !CloudInitScript::find($id)->count()){
            return false;
        }
        return $id && $id > 0;
    }

    /**
     * @return \MGProvision\Proxmox\v2\models\File|null
     */
    public function getSnippetFiles(){

        $serverConfiguration = new ServerConfigurationRepository($this->getWhmcsParamByKey('serverid'));
        if(!$serverConfiguration->snippetDirectory || !$serverConfiguration->snippetStorage){
            return;
        }
        $fileRepository = new FileRepository();
        $fileRepository->findByNodes([$this->getWhmcsCustomField(CustomField::NODE)])
            ->findSnippetsByServiceId($this->getWhmcsParamByKey('serviceid'))
            ->findByStorages([$serverConfiguration->snippetStorage]);
        return $fileRepository->fetch();

    }
}