<?php

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

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\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\AjaxFields\Select;

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

    public function prepareAjaxData()
    {
        session_write_close();
        //default node
        if($this->getRequestValue('location')){
            $defaultNode = $this->getRequestValue('location');
        }else{
            $defaultNode = $this->getNode()->getNode();
        }
        $storageRepository = new StorageRepository();
        $storageRepository->findByNodes([$defaultNode])
            ->findEnabed();
        $storages            = $storageRepository->fetchAsArray();
        $isoRepository = new FileRepository();
        $isoRepository->findByNodes([$defaultNode])
            ->findByStorages($storages);
        $isoRepository->findIso();

        foreach ($isoRepository->fetch() as $entity)
        {
            if ($this->configuration()->isPermissionSecondaryIsoImages() && !in_array($entity->getVolid(), $this->configuration()->getPermissionSecondaryIsoImages()))
            {
                continue;
            }

            $this->availableValues[]=[
                "key" => $entity->getVolid(),
                "value"     => $entity->getFriendlyName(),
            ];
        }
    }


}