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


use MGProvision\Proxmox\v2\models\Kvm;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\MigrateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\Reinstall\BackupVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\Reinstall\CreateVmJob;
use ModulesGarden\ProxmoxAddon\App\Jobs\Vps\Reinstall\DeleteVmJob;
use ModulesGarden\ProxmoxAddon\App\Libs\Format;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\AdminArea;
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;
use function ModulesGarden\Servers\ProxmoxVps\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'] = $this->getWhmcsCustomField('cipassword') ? $this->getWhmcsCustomField('cipassword') : htmlspecialchars($this->getWhmcsParamByKey("password"));
        }
    }

    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)),
        ];
        if ($this->configuration()->isBackupVmBeforeReinstall())
        {
            $job = queue(BackupVmJob::class, $arguments, null, "hosting", $this->getWhmcsParamByKey("serviceid"));
        }
        $job = queue(DeleteVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"));
        $job = queue(CreateVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"));
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The virtual server is being reinstalled')
            ->setCallBackFunction('mgLocationReload');

    }

    private function jobExist(){
        return Job::where("job", CreateVmJob::class. '@handle')->whereIn("status", ['waiting', "running", ""])
            ->where("rel_id", $this->getWhmcsParamByKey("serviceid"))
            ->where("rel_type", "hosting")->count() > 0;
    }

    public function processQemu()
    {
        if($this->jobExist()){
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate("Task 'Reinstall' already exist");
        }
        list($node, $vmid) = explode("/", $this->formData['id']);
        $vm = new Kvm($node, $vmid);
        $vm->setApi($this->api());
        $templateSize = $vm->getMasterHardDisk()->getBytes();
        if ($templateSize > $this->vm()->getMasterHardDisk()->getBytes())
        {
            sl("lang")->addReplacementConstant("size", Format::convertBytes($templateSize));
            return (new HtmlDataJsonResponse())
                ->setStatusError()
                ->setMessageAndTranslate('OS Template require disk size :size:');
        }
        //automaticaly configure administartor username for window
        $this->setHostingId($this->getWhmcsParamByKey('serviceid'));
        if( $this->configuration()->isAgent() &&
            $this->configuration()->isAgentServicePassword() &&
            !$this->configuration()->isAgentTemplateUser() &&
            preg_match('/w/', $vm ->config()['ostype'])){
            $ciuser =  $vm->config()['ciuser'];
            $this->hosting()->update(['username' => $ciuser ?: 'Administrator' ]);
        }
        elseif($this->configuration()->isQemu() && $this->configuration()->getCiuser()){
            $this->hosting()->update(['username' =>$this->configuration()->getCiuser() ]);
        }
        //update osTemplate in config
        // $this->hosting()->update(['customconfigoption[osTemplate]' => $this->formData['id']]);

        logModuleCall(
            'proxmoxCloud',
            __FUNCTION__,
            $this->configuration(),
            'Debug',
            $this->formData
        );

        $arguments = [
            'hostingId'  => $this->getWhmcsParamByKey('serviceid'),
            "osTemplate" => $this->formData['id'],
            "password"   => encrypt(html_entity_decode($this->formData['password'],ENT_QUOTES)),
        ];
        if ($this->configuration()->isBackupVmBeforeReinstall())
        {
            $job = queue(BackupVmJob::class, $arguments, null, "hosting", $this->getWhmcsParamByKey("serviceid"));
        }
        $job = queue(DeleteVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"));
        $job = queue(CreateVmJob::class, $arguments, $job->id, "hosting", $this->getWhmcsParamByKey("serviceid"));
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The virtual server is being reinstalled')
            ->setCallBackFunction('mgLocationReload');

    }

    public function iso()
    {

    }

}