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

use MGProvision\Proxmox\v2\models\MountPoint;
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 MountPointProvider extends BaseDataProvider implements ClientArea
{
    use ApiService;
    use ProductService;

    public function read()
    {
        if ($this->actionElementId && $this->actionElementId != "mountPointDataTable")
        {
            $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();

            $disk = $vm->getMounPoints()->findMountPointById($this->actionElementId);
            $this->data       = $disk->toArray();
            $this->data['id'] = $this->actionElementId;
            //backup
            $backup               = $this->data['backup'];
            $this->data['backup'] = $backup == "1" ? "on" : "off";
            //size
            $this->data['size'] = (int)$disk->getGb();
        }
    }

    public function create()
    {
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        //disk storage
        $storage              = $this->configuration()->getMountPointStorage();
        $mountPointRepository = $vm->getMounPoints();
        $hdd                  = new MountPoint($mountPointRepository->nextId());
        $vmModel->disks += $this->formData['size'];
        $hdd->setLocation($storage . ":" . $this->formData['size'])
            ->setAcl($this->configuration()->getMountPointAcl() == "default" ? null : $this->configuration()->getMountPointAcl())
            ->setRo($this->configuration()->isMountPointRo() ? 1 : null)
            ->setQuota($this->configuration()->isMountPointQuota() ? 1 : null)
            ->setBackup($this->configuration()->isPermissionMountPointBackup() && $this->formData['backup'] == "on" ? 1 : null)
            ->setReplicate($this->configuration()->isMountPointReplicate() ? '0' : null)
            ->setMp($this->formData['mp'])
            ->setPath($vm->getPath() . "/config")
            ->setApi($this->api())
            ->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();
        $hdd = $vm->getMounPoints()->findMountPointById($this->formData['id']);
        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);
        }
        if($hdd->isMaster()){
            $vm->config(true);
            $vmModel->disk =  (int)$this->formData['size'];
        }else{
            sleep(2);
            $vmModel->disks = $vm->getMounPoints()->additionalSize();
        }
        $vmModel->save();
        //backup
        $backup = $this->configuration()->isPermissionMountPointBackup() && $this->formData['backup'] == "on" ? 1 : null;
        if ($backup != $hdd->getBackup())
        {
            $hdd->setBackup($backup);
            $hdd->update();
        }
        //reboot
        $vmId = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->id;
        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->getMounPoints()->findMountPointById($this->formData['id']);
        if($hdd->getId() == "rootfs"){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('The master hard disk cannot be deleted');
        }
        $hdd->delete();
        foreach($vm->getMounPoints()->fetch() as $hd){
            if(preg_match('/unused/', $hd->getId())){
                $hd->delete();
                break;
            }
        }
        sleep(1);
        $vmModel->disks = $vm->getMounPoints()->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');
    }


}