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

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

    public function read()
    {
        if ($this->actionElementId && $this->actionElementId != "mountPointDataTable")
        {
            $disk = $this->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()
    {
        $this->resourceGuard()->mountPointLimit($this->formData['size']);
        //disk storage
        $storage              = $this->configuration()->getMountPointStorage();
        $mountPointRepository = $this->vm()->getMounPoints();
        $hdd                  = new MountPoint($mountPointRepository->nextId());
        $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($this->vm()->getPath() . "/config")
            ->setApi($this->api())
            ->create();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been created successfully')
            ->addData('createButtonStatus', $this->resourceGuard()->hasMountPointLimit())
            ->setCallBackFunction('pmToggleButton');
    }

    public function update()
    {
        $this->resourceGuard()->mountPointLimit($this->formData['size'], $this->formData['id']);
        $hdd = $this->vm()->getMounPoints()->findMountPointById($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->configuration()->isPermissionMountPointBackup() && $this->formData['backup'] == "on" ? 1 : null;
        if ($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()->hasMountPointLimit())
            ->setCallBackFunction('pmToggleButton');
    }

    public function delete()
    {
        $hdd =  $this->vm()->getMounPoints()->findMountPointById($this->formData['id']);
        if($hdd->getId() == "rootfs"){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('The master hard disk cannot be deleted');
        }
        $hdd->delete();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The hard disk has been deleted successfully')
            ->addData('createButtonStatus', $this->resourceGuard()->hasMountPointLimit())
            ->setCallBackFunction('pmToggleButton');
    }


}