<?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\ProxmoxVps\App\UI\Disk\Providers;

use MGProvision\Proxmox\v2\models\HardDisk;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\RebootVmJob;
use ModulesGarden\ProxmoxAddon\App\Models\Job;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use function ModulesGarden\ProxmoxAddon\Core\Helper\queue;


class DiskProvider extends BaseDataProvider implements ClientArea
{
    use ProductService;
    use ApiService;

    public function read()
    {
        if ($this->actionElementId && $this->actionElementId != "diskDataTable")
        {
            $disk = $this->vm()->findHardDiskById($this->actionElementId);
            $this->data       = $disk->getAttributes();
            $this->data['id'] = $this->actionElementId;
            //backup
            $backup               = $this->data['backup'];
            $this->data['backup'] = $backup == "0" ? "off" : "on";
            //size
            $this->data['size'] = $disk->getGb();
        }
    }

    public function create()
    {
        $this->resourceGuard()->diskLimit($this->formData['size']);
        $storage = $this->configuration()->getAdditionalDiskStorage();
        $ide     = $this->vm()->findFreeIde($this->formData['bus']);
        $id      = $this->formData['bus'] . $ide;
        $hdd     = new HardDisk($id);
        $hdd->setApi($this->api());
        $hdd->setPath($this->vm()->getPath() . "/config");
        $hdd->setStorage($storage)
            ->setSize($this->formData['size'])
            ->setMedia("disk")
            ->setFormat($this->formData['format'])
            ->setBackup($this->configuration()->isPermissionAdditionalDiskBackup() && $this->formData['backup'] == "on" ? null : 0);
        //disk speed
        $hdd->setMbps_rd($this->configuration()->getAdditionalDiskMbpsRd())
            ->setMbps_wr($this->configuration()->getAdditionalDiskMbpsWr());
        //IOPS
        $hdd->setIops_rd($this->configuration()->getAdditionalDiskIopsRd())
            ->setIops_rd_max($this->configuration()->getAdditionalDiskIopsRdMax())
            ->setIops_wr($this->configuration()->getAdditionalDiskIopsWr())
            ->setIops_wr_max($this->configuration()->getAdditionalDiskIopsWrMax());
        //cach
        $hdd->setCache($this->configuration()->getAdditionalDiskCache());
        //replicate
        if ($this->configuration()->isAdditionalDiskReplicate())
        {
            $hdd->setReplicate(0);
        }
        //discard
        if ($this->configuration()->isAdditionalDiskDiscard())
        {
            $hdd->setDiscard('on');
        }
        //iothread for VirtlO & SCSI 'VIRTIO', 'SCSI'
        if ($this->configuration()->isAdditionalDiskIoThread() && in_array($this->formData['bus'], ['virtio', 'scsi']))
        {
            $hdd->setIothread(1);
        }
        $hdd->create();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been created successfully')
            ->addData('createButtonStatus', $this->resourceGuard()->hasDiskLimit())
            ->setCallBackFunction('pmToggleButton');
    }

    public function update()
    {

        $this->resourceGuard()->diskLimit($this->formData['size'], $this->formData['id']);
        $hdd = $this->vm()->findHardDiskById($this->formData['id']);
        if($hdd->isMaster()){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Update the master disk size is restricted');
        }
        if ((int)$hdd->getGb() > (int)$this->formData['size'])
        {
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Downgrading the disk size is restricted');
        }
        //resize
        if ((int)$hdd->getGb() < (int)$this->formData['size'])
        {
            $size = "+" . abs((int)$this->formData['size'] - (int)$hdd->getGb()) . "G";
            $hdd->resize($size);
        }
        //backup
        $backup = $this->formData['backup'] == "on" ? null : 0;
        if ($this->configuration()->isPermissionAdditionalDiskBackup() && $backup != $hdd->getBackup())
        {
            $hdd->setBackup($backup);
            $hdd->update();
        }
        //reboot
        if ($this->vm()->isRunning() &&
            !Job::waiting()->ofJob(RebootVmJob::class)->ofHostingId($this->getWhmcsParamByKey("serviceid"))->count())
        {
            queue(RebootVmJob::class, [], null, "hosting", $this->getWhmcsParamByKey("serviceid"));
        }
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been updated successfully')
            ->addData('createButtonStatus', $this->resourceGuard()->hasDiskLimit())
            ->setCallBackFunction('pmToggleButton');
    }

    public function delete()
    {
        $hdd = $this->vm()->findHardDiskById($this->formData['id']);
        if($hdd->isMaster()){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('The master hard disk cannot be deleted');
        }
        $hdd->delete();
        unset($this->vm);
        foreach($this->vm()->getHardDisks() as $hd){
            if($hd->isMaster()){
                continue;
            }
            if(preg_match('/unused/', $hd->getId())){
                $hd->delete();
                break;
            }
        }
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been deleted successfully')
            ->addData('createButtonStatus', $this->resourceGuard()->hasDiskLimit())
            ->setCallBackFunction('pmToggleButton');
    }


}