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

use MGProvision\Proxmox\v2\repository\NodeRepository;
use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\MigrateVmJob;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
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 TemplateVmProvider extends BaseDataProvider implements ClientArea
{
    use ProductService;
    use ApiService;

    public function read()
    {
        if (!$this->actionElementId )
        {
            return;
        }
        foreach (VmModel::ofHostingId($this->getWhmcsParamByKey('serviceid'))->notTemplate()->get() as $item)
        {
            $this->availableValues['vmId'][$item->id] = $item->name;
        }
    }

    public function create()
    {
        $this->api();
        $this->networkService = new NetworkService();
        /**
         * @var VmModel $vmModel
         */
        $vmModel = VmModel::ofHostingId($this->getWhmcsParamByKey('serviceid'))
                            ->ofId($this->getFormDataValues()['vmId'])
                            ->firstOrFail();
        //VM
        $vm = (new VmFactory())->fromVmModel($vmModel);
        \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVm($vm);
        //Stop
        if($vm->isRunning()){
            $vm->stop();
            sleep(2);
        }
        //Delete interfaces & return ip addresses
        $this->networkService->deleteByIpAddresses($vmModel->virtualInterfaces);
        //Save description and reset config
        $config = [
            "name" => "custom{$this->getWhmcsParamByKey('serviceid')}-".$vmModel->name,
            'description'=> $this->getFormDataValues()['description'],
            'sockets' => 1,
            'cores' => 1,
            'vcpus' => 1,
            'memory' => 512,
            'ipconfig0' => '',
            'ciuser' => '',
            'cipassword' => '',
            'nameserver' => '',
            'ide2' => 'none,media=cdrom'
        ];
        $vm->updateConfig($config);
        //Convert to template
        $vm->convertToTemplate();
        $vmModel->template = 1;
        $vmModel->sockets = 0;
        $vmModel->cores = 0;
        $vmModel->vcpus = 0;
        $vmModel->memory = 0;
        $vmModel->save();
        sl("lang")-> addReplacementConstant("name",$vmModel->name);
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate("Virtual Machine :name: %s has been converted to template");
    }

    public function update()
    {
//        $vmModel = VmModel::ofHostingId($this->getWhmcsParamByKey('serviceid'))
//                            ->ofId($this->getFormDataValues()['vmId'])
//                            ->firstOrFail();
//        //VM
//        $vm = (new VmFactory())->fromVmModel($vmModel);
//        $attributes = [
//            "targetNode" => $this->formData['target'],
//            "online"     => $this->formData['online'] == "on" ? 1 : 0
//        ];
//        if (Job::where("job", MigrateVmJob::class. '@handle')->whereIn("status", ['waiting', "running", ""])
//                                                  ->where("rel_id", $this->getWhmcsParamByKey("serviceid"))
//                                                  ->where("rel_type", "hosting")
//                                                  ->where("custom_id", $vmModel->id)
//                                                  ->count())
//        {
//            return (new HtmlDataJsonResponse())
//                ->setStatusError()
//                ->setMessageAndTranslate("Task 'MigrateVm' already exist");
//        }
//        queue(MigrateVmJob::class, $attributes, null, "hosting", $this->getWhmcsParamByKey("serviceid"),$vmModel->id);
//        sl("lang")-> addReplacementConstant("vmid",$vm->getVmid())-> addReplacementConstant("node", $this->formData['target']);
//        return (new HtmlDataJsonResponse())
//            ->setStatusSuccess()
//            ->setMessageAndTranslate("Starting migration of VM :vmid: to :node:");
    }


}