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

use MGProvision\Proxmox\v2\models\HardDisk;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RebootVmJob;
use ModulesGarden\ProxmoxAddon\App\Models\Job;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
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\ProxmoxAddon\Core\Helper\queue;


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

    public function read()
    {
        if ($this->actionElementId && $this->actionElementId != "diskDataTable")
        {
            $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
            $disk = $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()
    {
        $storage = $this->configuration()->getAdditionalDiskStorage();
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmModel  = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $ide     = $vm->findFreeIde($this->formData['bus']);
        $id      = $this->formData['bus'] . $ide;
        $hdd     = new HardDisk($id);
        $hdd->setApi($this->api());
        $hdd->setPath($vm->getPath() . "/config");
        $hdd->setStorage($storage)
            ->setSize($this->formData['additionalDiskSize'])
            ->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);
        }
        $vmModel->disks += $this->formData['additionalDiskSize'];
        $hdd->create();
        $vmModel->save();
        $resourceManager = new ResourceManager();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been created successfully')
            ->addData('createButtonStatus', $resourceManager->disk()->hasFreeTotal())
            ->setCallBackFunction('pmToggleDiskButton');
    }

    public function update()
    {
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmModel  = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $vmId = $vmModel->id;
        $hdd = $vm->findHardDiskById($this->formData['id']);
        if ((int)$hdd->getGb() > (int)$this->formData['additionalDiskSize'])
        {
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('Downgrading the disk size is restricted');
        }
        //resize
        if ((int)$hdd->getGb() < (int)$this->formData['additionalDiskSize'])
        {
            $size = "+" . abs((int)$this->formData['additionalDiskSize'] - (int)$hdd->getGb()) . "G";
            $hdd->resize($size);
        }
        if($hdd->isMaster()){
            $vm->config(true);
            $vmModel->disk =  $vm->getMasterHddSize();
        }else{
            $vmModel->disks = $vm->getHardDiskRepostiory()->additionalSize();
        }
        $vmModel->save();
        //backup
        $backup = $this->formData['backup'] == "on" ? null : 0;
        $hdd->setBackup($backup)->update();
        if ($vm->isRunning() &&
            !Job::waiting()->ofJob(RebootVmJob::class)->ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofCustomId($vmId)->count())
        {
            queue(RebootVmJob::class, [], null, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        }
        $resourceManager = new ResourceManager();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been updated successfully')
            ->addData('createButtonStatus',$resourceManager->disk()->hasFreeTotal())
            ->setCallBackFunction('pmToggleDiskButton');
    }

    public function delete()
    {
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmModel  = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $hdd = $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($vm->getHardDisks() as $hd){
            if($hd->isMaster()){
                continue;
            }
            if(preg_match('/unused/', $hd->getId())){
                $hd->delete();
                break;
            }
        }

        $vmModel->disks = $vm->getHardDiskRepostiory()->additionalSize();
        $vmModel->save();
        $resourceManager = new ResourceManager();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been deleted successfully')
            ->addData('createButtonStatus', $resourceManager->disk()->hasFreeTotal())
            ->setCallBackFunction('pmToggleDiskButton');
    }


}