<?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\Vms\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\ProductService;
use ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AdminArea;
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 MigrateProvider extends BaseDataProvider implements AdminArea
{
    use ProductService;
    use ApiService;

    public function read()
    {
        if (!$this->actionElementId )
        {
            return;
        }
        $this->api();
        $vmModel = VmModel::ofHostingId($this->getWhmcsParamByKey('serviceid'))
            ->ofId($this->actionElementId)
            ->firstOrFail();
        $this->data['vmId'] = $vmModel->id;
        //VM
        $vm = (new VmFactory())->fromVmModel($vmModel);
        if ($vm->isRunning())
        {
            $this->data['online'] = "on";
        }
        $nodeRepository = new NodeRepository();
        $nodeRepository->setApi($this->api());
        $nodeRepository->findOnline(true);
        foreach ($nodeRepository->fetch() as $item)
        {
            if ($item->getNode() == $vm->getNode())
            {
                continue;
            }
            $this->availableValues['target'][$item->getNode()] = $item->getNode();
        }
    }

    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:");
    }


}