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

use MGProvision\Proxmox\v2\ProxmoxApiException;
use MGProvision\Proxmox\v2\repository\StorageRepository;
use ModulesGarden\ProxmoxAddon\App\Models\NodeSetting;
use ModulesGarden\ProxmoxAddon\App\Services\BaseService;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

/**
 *
 * Description of RangeVmProvider
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class NodeSettingProvider extends BaseModelDataProvider implements AdminArea
{
    use BaseService;

    public function __construct()
    {
        parent::__construct(NodeSetting::class);
    }

    public function read()
    {
        if (!$this->actionElementId)
        {
            return false;
        }
        $this->data['node']      = $this->actionElementId;
        $this->data['server_id'] = $this->getRequestValue('id');
        $query                   = NodeSetting::ofServer($this->getRequestValue('id'))
            ->ofNode($this->data['node']);
        foreach ($query->get() as $nodeSetting)
        {

            $this->data[$nodeSetting->setting] = $nodeSetting->value;
        }
        if (isset($this->data['vmCreate']))
        {
            $vmCreate               = $this->data['vmCreate'];
            $this->data['vmCreate'] = $vmCreate == 1 ? "on" : "off";
        }
        $this->loadDefaultStorages();

        sl('lang')->addReplacementConstant('node', $this->data['node']);
    }

    private function loadDefaultStorages(){
        //defaultStorage
        $this->availableValues['defaultStorage'][0] = sl("lang")->tr("None");
        if(!$this->data['node']){
            return;
        }
        try{
            $this->loadRequestObj()->setServerId($this->getRequestValue('id'))->getApi()->setInstance();

            $storageRepository = new StorageRepository();
            $storageRepository->findByNodes([$this->data['node']])
                              ->findEnabed();
            foreach ($storageRepository->fetch() as $entity)
            {
                if (!in_array("images", $entity->getContentAsArray()))
                {
                    continue;
                }
                $this->availableValues['defaultStorage'][$entity->getStorage()] = $entity->getStorage();
            }
        }catch (ProxmoxApiException $ex){
        }
    }
    public function update()
    {
        $fillable                   = ['vmCreate', 'vmsMax', 'cpuMax', 'diskMax', 'ramMax', 'defaultStorage'];
        $vmCreate                   = $this->formData['vmCreate'];
        $this->formData['vmCreate'] = $vmCreate == "on" ? 1 : 0;
        foreach ($this->formData as $key => $value)
        {
            if (!in_array($key, $fillable))
            {
                continue;
            }
            //Create & update
            if (isset($value))
            {
                $entity = NodeSetting::OfServer($this->formData['server_id'])->ofNode($this->formData['node'])->ofSetting($key)->first();
                if (!$entity)
                {
                    $entity = new NodeSetting();
                }
                $entity->fill(['node' => $this->formData['node'], 'server_id' => $this->formData['server_id'], 'setting' => $key, 'value' => $value])
                    ->save();
                //Delete
            }
            else
            {
                if (empty($value))
                {
                    NodeSetting::OfServer($this->formData['server_id'])->ofNode($$this->formData['node'])->ofSetting($key)->delete();
                }
            }
        }
        sl('lang')->addReplacementConstant('node', $this->formData['node']);
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('The settings for the node :node: has been edited successfully');
    }
}
