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

use MGProvision\Proxmox\v2\ProxmoxApiException;
use MGProvision\Proxmox\v2\repository\StorageRepository;
use ModulesGarden\ProxmoxAddon\App\Models\RangeVm;
use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
use ModulesGarden\ProxmoxAddon\App\Services\BaseService;
use ModulesGarden\ProxmoxAddon\Core\DependencyInjection;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Server;
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 RangeVmProvider
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class ServerSettingProvider extends BaseDataProvider implements AdminArea
{
    use BaseService;

    protected $rangeVm;
    /**
     * @var ServerConfigurationRepository
     */
    protected $serverConfiguration;

    public function __construct()
    {
        $this->rangeVm = DependencyInjection::create(RangeVm::class);
        $this->serverConfiguration = new ServerConfigurationRepository($this->getRequestValue('id'));
        parent::__construct();
    }

    public function read()
    {

        $dbData = $this->rangeVm->where('server_id', $this->getRequestValue('id'))->first();
        if ($dbData !== null)
        {
            $this->data = $dbData->toArray();
        }
        $this->data['server_id'] = $this->getRequestValue('id');
        foreach ($this->serverConfiguration->all() as $key => $value){
            $this->data[$key] = $value;
        }
        $this->data['sshPassword'] = $this->serverConfiguration->getSshPassword();
        $this->data['sshKey'] = $this->serverConfiguration->getSshKey();
        //snippetStorage
        try{
            $this->availableValues['snippetStorage'] = [];
            $this->setServerId($this->getRequestValue('id'));
            $this->getApi()->setInstance();
            $repository = new StorageRepository();
            $repository->findSnippets();
            foreach (     $repository->fetch() as $storage){
                $this->availableValues['snippetStorage'][$storage->getStorage()] = $storage->getStorage();
            }
        }catch (ProxmoxApiException $ex){
            //nothing to do
        }
    }

    public function update()
    {
        //update & create range vnm
        if ($this->getFormDataValues()['vmid_from'] && $this->formData['vmid_to'])
        {
            $dbData = $this->rangeVm->where('server_id', $this->formData['server_id'])->first();
            if ($dbData === null)
            {
                $dbData = new RangeVm();
            }
            $dbData->fill($this->formData)->save();
        }
        else
        {//delete range vm
            $this->rangeVm->where('server_id', $this->formData['server_id'])->delete();
        }
        $data = [
            'sshHost' =>  $this->formData['sshHost'],
            'sshPort' =>  $this->formData['sshPort'],
            'sshUser' =>  $this->formData['sshUser'],
            'sshPassword' =>  encrypt($this->formData['sshPassword']),
            'sshKey' =>  encrypt($this->formData['sshKey']),
            'snippetStorage' =>  $this->formData['snippetStorage'],
            'snippetDirectory' => null,
        ];
        if($this->formData['snippetStorage']){
            $this->setServerId($this->formData['server_id']);
            $this->getApi()->setInstance();
            $repository = new StorageRepository();
            $repository->findSnippets();
            foreach (     $repository->fetch() as $storage){
                if($storage->getStorage() == $this->formData['snippetStorage']){
                    $data['snippetDirectory'] = sprintf("%s/snippets/", $storage->getPath());
                    break;
                }
            }
        }
        $this->serverConfiguration->fillAndSave($data);


        return (new HtmlDataJsonResponse())->setMessageAndTranslate('The server settings has been edited successfully')
            ->setStatusSuccess()
            ->setCallBackFunction($this->callBackFunction);
    }
}
