<?php

namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Fields;

use MGProvision\Proxmox\v2\repository\ClusterResourcesRepository;
use MGProvision\Proxmox\v2\repository\FileRepository;
use MGProvision\Proxmox\v2\repository\StorageRepository;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\Core\Helper\AdvancedUserHelper;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\AjaxFields\Select;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class OsTemplateSelect extends Select implements ClientArea {
    use ProductService;
    use ApiService;

    public function prepareAjaxData() {
        session_write_close();
        $advancedUser = new AdvancedUserHelper($this->getWhmcsParamByKey('userid'));
        if ($this->configuration()->isQemu()) {
            $this->loadQemuTemplates();

/*            if ($advancedUser->isAdvanced() || $this->configuration()->isPermissionIsoImage())
            {
                $this->availableValues[] = [
                    "key"   => 'installationFromIso',
                    "value" => sl('lang')->abtr('Installation From ISO'),
                ];
            }
            if($this->availableValues[0]['key']=="installationFromIso"){
                $this->callBackFunction = 'pcOsTemplateLoadShowIsoFields';
            } */
        }
        if ($this->configuration()->isLxc())  {
            $this->loadLxcTemplates();
        }
        if($this->availableValues[0]['key']){
            $this->value = $this->availableValues[0]['key'];
        }

        $this->data['additionalData']['showItemDescription']  = true;
    }

    private function defaultNode()  {
        if ($this->getRequestValue('location')) {
            return $this->getRequestValue('location');
        } else {
            return $this->getNode()->getNode();
        }
    }

    private function loadQemuTemplates() {
        $clusterResurces = new ClusterResourcesRepository();
        $clusterResurces->findKvmTemplate();
        //default node
        $defaultNode = $this->defaultNode();
        //search templates on specific node
        if (!$this->configuration()->isOsTemplatesInAllNodes())  {
            $clusterResurces->findByNodes($defaultNode);
        }

        $VmList = $clusterResurces->fetchWithUniqueNames($defaultNode);
        usort($VmList, function($a, $b) {return strcmp($a->getName(), $b->getName());});
        foreach ($VmList as $entity)    {
            if ($entity->isCustom() && !$entity->matchName($this->getWhmcsParamByKey("serviceid")))  {
                continue;
            }
            if (!$entity->isCustom() && $this->configuration()->isPermissionOsTemplates() && !in_array($entity->getName(), $this->configuration()->getPermissionOsTemplates())) {
                continue;
            }
            $id = "{$entity->getNode()}/{$entity->getVmid()}";
            $name = sl('lang')->abtr('template', $entity->getName());
            $description = $entity->getVm()->config()['description'];
            if(!$description){
                $description = $entity->getName();
            }
            $description = str_replace('\n','<br />', $description);
            $desc = sl('lang')->abtr('template_desc',$description );
            $desc = nl2br($desc);

            $this->availableValues[] = [
                "key" => $id,
                "value" => $name,
                'description' => $name != $desc ? $desc : null,
            ];

        }
    }

    private function loadLxcTemplates()   {
        $defaultNode = $this->defaultNode();
        $storageRepository = new StorageRepository();
        $storageRepository->findByNodes([$defaultNode])->findEnabed();
        $fileRepository = new FileRepository();
        $fileRepository->setApi($this->api());
        $fileRepository->findLxcTemplates();
        $fileRepository->findByNodes([$defaultNode]);
        $fileRepository->findByStorages($storageRepository->fetchAsArray());
        foreach ($fileRepository->fetch() as $file) {
            if ($this->configuration()->isPermissionOsTemplates() && !in_array($file->getVolid(), $this->configuration()->getPermissionOsTemplates())) {
                continue;
            }
            $this->availableValues[] = [
                "key" => $file->getVolid(),
                "value" => sl('lang')->abtr('template', $file->getFriendlyName()),
            ];
        }
    }


}