<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (27.03.19)
* *
*
*  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
*  CONTACT                        ->       contact@modulesgarden.com
*
*
* This software is furnished under a license and may be used and copied
* only  in  accordance  with  the  terms  of such  license and with the
* inclusion of the above copyright notice.  This software  or any other
* copies thereof may not be provided or otherwise made available to any
* other person.  No title to and  ownership of the  software is  hereby
* transferred.
*
*
* ******************************************************************** */

namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Reinstall\Providers;


use MGProvision\Proxmox\v2\repository\FileRepository;
use MGProvision\Proxmox\v2\repository\SnapshotRepository;
use MGProvision\Proxmox\v2\repository\StorageRepository;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\IpSetIpFilterService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class IsoInstallProvider extends BaseDataProvider implements ClientArea
{
    use ProductService;
    use ApiService;
    /**
     * @var HighAvailabilityClusterService
     */
    private $highAvailabilityClusterService;
    /**
     * @var IpSetIpFilterService
     */
    private $ipSetIpFilterService;

    public function read()
    {
        if ($this->actionElementId)
        {
            $this->data['id'] = $this->actionElementId;
        }
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $storageRepository = new StorageRepository();
        $storageRepository->findByNodes([$vm->getNode()])
             ->findEnabed();
        $storages            = $storageRepository->fetchAsArray();
        $isoRepository = new FileRepository();
        $isoRepository->findByNodes([$vm->getNode()])
                      ->findByStorages($storages);
        $isoRepository->findIso();
        $this->availableValues['secondaryIsoImage'][0] = sl('lang')->abtr("None");
        foreach ($isoRepository->fetch() as $entity)
        {
            if ($this->configuration()->isPermissionSecondaryIsoImages() && !in_array($entity->getVolid(), $this->configuration()->getPermissionSecondaryIsoImages()))
            {
                continue;
            }
            $this->availableValues['secondaryIsoImage'][$entity->getVolid()] = sl('lang')->abtr( "template", $entity->getFriendlyName());
        }
    }

    public function update()
    {

    }

    private function initServices()
    {
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
        $this->ipSetIpFilterService           = new IpSetIpFilterService();
    }

    public function processQemu()
    {
        $this->initServices();
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        //Empyty template
        if (!$this->formData['id'])
        {
            throw new \Exception ("Provide OS Template");
        }
        $spanshootRepostiory = new SnapshotRepository();
        $spanshootRepostiory->findByVm($vm)
            ->ignoreCurrent(true);
        if ($spanshootRepostiory->count())
        {
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Remove the snapshots before reinstallation.');
        }
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->data['osTemplate'] =   null;
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->save();
        //ha
        if ($this->highAvailabilityClusterService->exist())
        {
            $this->highAvailabilityClusterService->delete();
        }
        //stop
        if ($vm->isRunning())
        {
            $vm->stop();
        }
        //Remove cloud-init drive
        foreach ($vm->config() as $id => $v)
        {
            if (preg_match('/cloudinit/', $v))
            {
                $vm->deleteConfig($id);
            }
        }
        //insert unattended iso
        $cdroms = $vm->getCdRom()->fetch();
        if(!$cdroms[0] || ($this->formData['secondaryIsoImage'] && !$cdroms[1])){
            throw new \MGProvision\Proxmox\v2\ProxmoxApiException("CD-ROM volume not found");
        }
        $cdroms[0]->setLocation($this->formData['id'])->update();
        //secondaryIsoImage
        if($this->formData['secondaryIsoImage'] ){
            $cdroms[1]->setLocation($this->formData['secondaryIsoImage'])->update();
        }
        //remove hard drive and recreate a new one, (the drive have to be empty)
        $masterHdd = $vm->getMasterHardDisk();
        $masterHdd->delete();
        sleep(1);
        //Delete Unused Disk
        foreach ($vm->config(true) as $id => $v)
        {
            if (preg_match('/unused/', $id))
            {
                $vm->deleteConfig($id);
            }
        }
        //create new disk
        $bytes = $masterHdd->getBytes();
        $size  = (int)$bytes / pow(1024, 3);
        $masterHdd->setSize($size);
        $masterHdd->create();
        sleep(1);
        //Boot disk
        $vm->updateConfig(['bootdisk' => $masterHdd->getId()]);
        //set bootorder to disk, cdrom, network (if cdrom would be first, the installer will run on every boot -> bootloop)
        $vm->changeBootOrder('cdn');
        //ipset
        if ($this->configuration()->isIpsetIpFilter())
        {
            $this->ipSetIpFilterService->create();
        }
        //HA
        if ($this->configuration()->getClusterState())
        {
            $this->highAvailabilityClusterService->create();
        }
        //start vps
        $vm->start();
        //show message that installation is now processing. The login information will be available in the noVNC console after installation.
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('Installation is now processing. The login information will be available in the noVNC console.');

    }

}