<?php

/* * ********************************************************************
 * ProxmoxAddon product developed. (Aug 23, 2018)
 * *
 *
 *  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\ProxmoxAddon\App\UI\Templates\Providers;

use MGProvision\Proxmox\v2 as proxmox;
use ModulesGarden\ProxmoxAddon as main;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;

/**
 *
 * Description of RangeTemplateProvider
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class TemplateProvider extends BaseDataProvider implements AdminArea
{

    use main\App\Services\BaseService;

    public function read()
    {
        if (!$this->actionElementId)
        {
            return false;
        }
        $this->data             = json_decode(base64_decode($this->actionElementId), true);
        $this->data['serverId'] = $this->getRequestValue('id');
    }

    public function delete()
    {
        $this->setServerId($this->formData['serverId']);
        $this->getApi()->setInstance();
        $this->getVm($this->formData['node'], $this->formData['vmid'], $this->formData['type'])->delete();
        main\Core\ServiceLocator::call('lang')->addReplacementConstant('name', $this->formData['name']);
        sleep(1);
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('Deleting template :name: in progress');
    }

    private function getVm($node, $vmid, $type)
    {
        switch ($type)
        {
            case 'qemu' :
                $vm = new proxmox\models\Kvm($node, $vmid);
                break;
            case 'lxc':
                $vm = new proxmox\models\Lxc($node, $vmid);
                break;
            default :
                throw new \Exception(sprintf("Unkown virtualization %s type", $type));
        }
        return $vm;
    }

    public function deleteMass()
    {
        if (!$this->getRequestValue('massActions'))
        {
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('Bug no massActions data!')->setStatusError();
            return;
        }
        $this->setServerId($this->getRequestValue('id'));
        $this->getApi()->setInstance();
        foreach ($this->getRequestValue('massActions') as $id)
        {
            $data = json_decode(base64_decode($id), true);
            $this->getVm($data['node'], $data['vmid'], $data['type'])->delete();
        }
        sleep(1);
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('Deleting the selected templates in progress');
    }

    public function update()
    {
        $this->setServerId($this->formData['serverId']);
        $this->getApi()->setInstance();
        $vm = $this->getVm($this->formData['node'], $this->formData['vmid'], $this->formData['type']);
        $vm->updateConfig(["ciuser" => $this->formData['ciuser'], "description" => $this->formData['description'] ]);
        //Update ciuser
        if ($this->formData['ciuser'])
        {
            $vm->updateConfig(["ciuser" => $this->formData['ciuser'], "description" => $this->formData['description'] ]);
        }
        else
        {
            //Delete ciuser
            $vm->deleteConfig('ciuser');
        }
        main\Core\ServiceLocator::call('lang')->addReplacementConstant('name', $this->formData['name']);
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('Template :name: has been updated.');
    }

    public function create()
    {
        $this->setServerId($this->formData['serverId']);
        $this->getApi()->setInstance();
        $resurcesRepostiory = new proxmox\repository\ClusterResourcesRepository();
        $resurcesRepostiory->findVm();
        foreach ($resurcesRepostiory->fetch() as $resurce)
        {
            if ($resurce->getVmid() == $this->formData['vmid'])
            {
                $vm = $resurce->getVm();
                break;
            }
        }
        if (!$vm)
        {
            main\Core\ServiceLocator::call('lang')->addReplacementConstant('vmid', $this->formData['vmid']);
            return (new HtmlDataJsonResponse())->setMessageAndTranslate('Virtual Machine :vmid: has not been found')->setStatusError();
        }
        /* @var $vm proxmox\models\Kvm */
        if ($vm->isRunning())
        {
            $vm->stop();
            sleep(20);
        }
        $vm->updateConfig(["description" => $this->formData['description'], 'ciuser' => $this->formData['ciuser']]);
        sleep(2);
        $vm->convertToTemplate();
        sleep(1);
        main\Core\ServiceLocator::call('lang')->addReplacementConstant('name', $resurce->getName());
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('Virtual Machine :name: has been converted to template successfully.');
    }
}
