<?php

namespace ModulesGarden\ProxmoxAddon\App\Services\Cloud;


use MGProvision\Proxmox\v2\models\HardDisk;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

class AdditionalDiskService
{
    use WhmcsParams;
    use ApiService;
    use ProductService;

    public function hasDisk(){

        foreach (sl('Vm')->getVm()->getHardDisks() as $hardDisk)
        {
            if (!$hardDisk->isMaster())
            {
                return true;
            }
        }
        return false;
    }

    public function create($config){
        for ($i=1; $i<=10; $i++){
            $diskSize = (int) $config['additionalDiskSize'.$i];
            if(!$diskSize){
                continue;
            }
            $type = $config['additionalDiskBus'.$i];
            $bus = sl('Vm')->getVm()->findFreeDeviceId($type);
            $harDisk = new HardDisk($type . $bus);
            $harDisk->setSize($diskSize)
                ->setApi($this->api())
                ->setPath(sl('Vm')->getVm()->getPath() . "/config")
                ->setMedia("disk")
                ->setBackup( $config['additionalDiskBackup'.$i]== "on" ? null : 0)
                ->setStorage($this->configuration()->getAdditionalDiskStorage())
                ->setCache($this->configuration()->getAdditionalDiskCache())
                ->setFormat($config['additionalDiskFormat'.$i])
                ->setMbps_rd($this->configuration()->getAdditionalDiskMbpsRd())
                ->setMbps_wr($this->configuration()->getAdditionalDiskMbpsRd())
                ->setDiscard($this->configuration()->isAdditionalDiskDiscard() ? "on" : null)
                ->setIops_rd($this->configuration()->getAdditionalDiskIopsRd())
                ->setIops_rd_max($this->configuration()->getAdditionalDiskIopsRdMax())
                ->setIops_wr($this->configuration()->getAdditionalDiskIopsWr())
                ->setIops_wr_max($this->configuration()->getAdditionalDiskIopsWrMax())
                ->setReplicate($this->configuration()->isAdditionalDiskReplicate() ? 0 : null);
            if ($this->configuration()->isAdditionalDiskIoThread() && in_array($type, ['virtio', 'scsi']))
            {
                $harDisk->setIothread(1);
            }
            $harDisk->create();
        }
    }

}