<?php


namespace ModulesGarden\Servers\ProxmoxVps\App\UI\Reinstall\Pages;


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\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Reinstall\Buttons\TemplateInstallButton;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\sl;

trait TemplateTrait
{
    use ApiService;
    use ProductService;

    public function initContent()
    {
        $this->setInternalAlertMessage("Select the template for reinstallation. If you proceed, all data located on the virtual machine will be lost.");
        //Update
        $this->addActionButton(new TemplateInstallButton());
    }

    protected function loadHtml()
    {
        $this->addColumn((new Column('name'))->setSearchable(true, "string")->setOrderable('ASC'));
    }

    public function replaceFieldName($key, $row)
    {
        return sl("lang")->abtr("template", $row[$key]);
    }

    protected function loadData()
    {
        $data           = [];
        $fileRepository = new FileRepository();
        $nodes          = [$this->vm()->getNode()];
        //LXC
        if ($this->configuration()->isLxc())
        {
            $storageRepository = new StorageRepository();
            $storageRepository->findByNodes($nodes);
            $storageRepository->findEnabed();
            $storages = $storageRepository->fetchAsArray();
            $fileRepository->findByNodes($nodes)
                ->findByStorages($storages);
            $fileRepository->findByContent('vztmpl');
            foreach ($fileRepository->fetch() as $entity)
            {
                if ($this->configuration()->isPermissionOsTemplates() && !in_array($entity->getVolid(), $this->configuration()->getPermissionOsTemplates()))
                {
                    continue;
                }
                $data[] = [
                    "id"   => $entity->getVolid(),
                    "name" => $entity->getFriendlyName(),
                ];
            }
        }//KVM
        else
        {
            if ($this->configuration()->isQemu())
            {
                $clusterResurces = new ClusterResourcesRepository();
                $clusterResurces->findKvmTemplate();
                if (!$this->configuration()->isOsTemplatesInAllNodes())
                {
                    $clusterResurces->findByNodes($this->vm()->getNode());
                }

                foreach ($clusterResurces->fetchWithUniqueNames($this->vm()->getNode()) as $entity)
                {
                    if ($entity->isCustom() && !$entity->matchName($this->getWhmcsParamByKey("serviceid")))
                    {
                        continue;
                    }
                    if ($this->configuration()->isPermissionOsTemplates() && !in_array($entity->getName(), $this->configuration()->getPermissionOsTemplates()))
                    {
                        continue;
                    }
                    $id     = "{$entity->getNode()}/{$entity->getVmid()}";
                    $data[] = [
                        "id" => $id,
                        "name"     => $entity->getName(),
                    ];
                }
            }
        }
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting("name", 'ASC');
        $dataProv->setData($data);
        $this->setDataProvider($dataProv);
    }

}