<?php


namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\MountPoint\Validators;


use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\Validators\BaseValidator;

class DiskSizeValidator extends BaseValidator
{
    protected $minValue = 0;
    protected $maxValue = 0;
    protected $required = true;

    public function __construct( $required = true)
    {
        $this->required = $required;
    }

    protected function validate($data, $additionalData = null)
    {
        if (!$this->required && empty($data))
        {
            return true;
        }
        $resurceManager = new ResourceManager();
        $diskId = $additionalData->get('formData')['id'];
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $size = $vm->getMounPoints()->findMountPointById($diskId)->getGb();
        $diskResource =    $resurceManager ->disk();
        $diskResource->setUsed($diskResource->getUsed() - $size);
        $this->maxValue = $diskResource->free();
        $this->minValue =  $diskResource->getMin();

        if(preg_match("/\./", $data)){
            $this->addValidationError('PleaseProvideANumericValueBetween', false, ['minValue' => $this->minValue, 'maxValue' => $this->maxValue]);
            return false;
        }
        if (is_numeric($data) && $this->minValue === 0 && $this->maxValue === 0)
        {
            return true;
        }
        //Min & Max
        if (is_numeric($data) && $this->minValue <= ((int)$data) && ((int)$data) <= $this->maxValue)
        {
            return true;
        }
        //Min
        else
        {
            if (is_numeric($data) && !is_numeric($this->maxValue) && $this->minValue <= ((int)$data))
            {
                return true;
            }
        }

        if ($this->minValue === $this->maxValue)
        {
            $this->addValidationError('PleaseProvideANumericValue');

            return false;
        }

        if (is_numeric($this->minValue) && is_numeric($this->maxValue))
        {
            $this->addValidationError('PleaseProvideANumericValueBetween', false, ['minValue' => $this->minValue, 'maxValue' => $this->maxValue]);
        }
        else
        {
            if (is_numeric($this->minValue) && !is_numeric($this->maxValue))
            {
                $this->addValidationError('PleaseProvideANumericValueFrom', false, ['minValue' => $this->minValue]);
            }
        }


        return false;
    }

}