<?php


namespace ModulesGarden\ProxmoxAddon\App\Services\Vps;

use MGProvision\Proxmox\v2\models\MountPoint;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;

class AdditionalMountPointService
{
    use WhmcsParams;
    use ApiService;
    use ProductService;

    public function hasMountPoint(){
        foreach ($this->vm()->getMounPoints()->fetch() as $mounPoint){
            if($mounPoint->isMaster()){
                continue;
            }
            return true;
        }
        return false;
    }

    public function create(){
        $size = $this->getSize();
        if(!$size ||   $size == "-1"){
            return;
        }
        $storage = $this->configuration()->getMountPointStorage();
        $mountPointRepository = $this->vm()->getMounPoints();
        $hdd = new MountPoint($mountPointRepository->nextId());
        $hdd->setLocation($storage . ":" . $size )
            ->setAcl($this->configuration()->getMountPointAcl() == "default" ? null : $this->configuration()->getMountPointAcl())
            ->setRo($this->configuration()->isMountPointRo() ? 1 : null)
            ->setQuota($this->configuration()->isMountPointQuota() ? 1 : null)
            ->setBackup(null)
            ->setReplicate($this->configuration()->isMountPointReplicate() ? '0' : null)
            ->setMp('/additional')
            ->setPath($this->vm()->getPath() . '/config')
            ->setApi($this->api())
            ->create();
        if($this->configuration()->isPermissionMountPointBackup()){
            $hdd->setBackup(1);
        }
    }

    private function getSize(){
        $diskSize = $this->configuration()->getAdditionalDiskSize();
        if ($this->isWhmcsConfigOption(ConfigurableOption::ADDITIONAL_DISKS_SIZE))
        {
            $diskSize = $this->getWhmcsConfigOption(ConfigurableOption::ADDITIONAL_DISKS_SIZE);
            Utility::unitFormat($diskSize, $this->configuration()->getAdditionalDiskUnit(), 'gb');
        }
        return $diskSize;
    }

    public function resize(){
        $diskSize = $this->getSize();
        if(!$diskSize || $diskSize == "-1" ){
            return;
        }
        foreach ($this->vm()->getMounPoints()->fetch() as $mounPoint){
            if($mounPoint->isMaster()){
                continue;
            }
            if((int)$mounPoint->getGb() == (int) $diskSize ){
                return true;
            }
            if((int)$mounPoint->getGb() > (int) $diskSize){
                throw new \InvalidArgumentException("Downgrading the mount point size is restricted");
            }
            $size = "+" . abs((int)$diskSize - (int)$mounPoint->getGb()) . "G";
            $mounPoint->resize($size);
            return true;
        }
    }
}