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


use MGProvision\Proxmox\v2\models\Kvm;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall\BackupVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall\CreateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Reinstall\DeleteVmJob;
use ModulesGarden\ProxmoxAddon\App\Libs\Format;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AdminArea;
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;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;


class TemplateInstallProvider extends BaseDataProvider implements ClientArea, AdminArea
{
    use ProductService;
    use ApiService;
    use HostingService;

    public function read()
    {
        if ($this->actionElementId)
        {
            $this->data['id']       = $this->actionElementId;
            $this->data['password'] =  \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->getPassword();
        }
    }

    public function update()
    {

    }

    public function processLxc()
    {
        if($this->jobExist()){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate("Task 'Reinstall' already exist");
        }
        $arguments = [
            'hostingId'  => $this->getWhmcsParamByKey('serviceid'),
            "osTemplate" => $this->formData['id'],
            "password"   => encrypt(html_entity_decode($this->formData['password'],ENT_QUOTES)),
        ];
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->data['osTemplate'] =   $this->formData['id'];
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->save();
        $vmId = $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->id;
        if ($this->configuration()->isBackupVmBeforeReinstall())
        {
            $job = queue(BackupVmJob::class, $arguments, null, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        }
        $job = queue(DeleteVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        $job = queue(CreateVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The virtual server is being reinstalled')
            ->setCallBackFunction('mgLocationReload');

    }

    private function jobExist(){
        $vmId = $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->id;
        return Job::where("job", CreateVmJob::class. '@handle')->whereIn("status", ['waiting', "running", ""])
            ->where("rel_id", $this->getWhmcsParamByKey("serviceid"))
            ->where("rel_type", "hosting")
                ->where("custom_id", $vmId)
                ->count() > 0;
    }

    public function processQemu()
    {
        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmId =  \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->id;
        if($this->jobExist()){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate("Task 'Reinstall' already exist");
        }
        list($node, $vmid) = explode("/", $this->formData['id']);
        $vmTemplate = new Kvm($node, $vmid);
        $vmTemplate ->setApi($this->api());
        $templateSize =  $vmTemplate->getMasterHardDisk()->getBytes();
        if ($templateSize > $vm->getMasterHardDisk()->getBytes())
        {
            sl("lang")->addReplacementConstant("size", Format::convertBytes($templateSize));
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('OS Template require disk size :size:');
        }
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->data['osTemplate'] =  $vmTemplate->status()['name'];
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->save();
        $arguments = [
            'hostingId'  => $this->getWhmcsParamByKey('serviceid'),
            "osTemplate" => $this->formData['id'],
            "password"   => encrypt(html_entity_decode($this->formData['password'],ENT_QUOTES)),
        ];
        //automaticaly configure administartor username for window
        $this->setHostingId($this->getWhmcsParamByKey('serviceid'));
        if( $this->configuration()->isAgent() &&
            $this->configuration()->isAgentPassword() &&
            preg_match('/w/', $vmTemplate ->config()['ostype'])){
            $arguments['username'] =  'Administrator';
        }
        elseif($this->configuration()->isQemu() && $this->configuration()->getCiuser()){
            $arguments['username'] = $this->configuration()->getCiuser();
        }
        if ($this->configuration()->isBackupVmBeforeReinstall())
        {
            $job = queue(BackupVmJob::class, $arguments, null, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        }
        $job = queue(DeleteVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        $job = queue(CreateVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmId);
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The virtual server is being reinstalled')
            ->setCallBackFunction('mgLocationReload');

    }

    public function iso()
    {

    }

}