<?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\ProxmoxVps\App\UI\ServiceInformation\Providers;

use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\Lxc;
use MGProvision\Proxmox\v2\models\NetworkDeviceKvm;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\isAdmin;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\sl;


class UpdateProvider extends BaseDataProvider implements ClientArea
{
    use ApiService;
    use ProductService;
    use HostingService;

    public function read()
    {
        if ($this->vm() instanceof Kvm)
        {
            //hostname
            $this->data['hostname'] = $this->vm()->config()['name'];
            //ISO
            if(isAdmin() || $this->configuration()->isPermissionIsoImage()){
                $this->data['iso']            = $this->vm()->cdrom()['isoRaw'];
                $this->availableValues['iso'] = ["none" => sl("lang")->abtr("template", "None")];

                foreach ($this->isoRepository()->fetch() as $file)
                {
                    if ($this->configuration()->isPermissionIsoImages() && !in_array($file->getVolid(), $this->configuration()->getPermissionIsoImages()))
                    {
                        continue;
                    }
                    $this->availableValues['iso'][$file->getVolid()] = sl("lang")->abtr("template", $file->getFriendlyName());
                }
            }
            //Boot order
            $bootOrder                           = $this->vm()->getBootOrder();
            $this->data['bootOrder0']            = $bootOrder[0];
            $this->data['bootOrder1']            = $bootOrder[1];
            $this->data['bootOrder2']            = $bootOrder[2];
            $options                             = [
                0   => sl("lang")->tr("None"),
                "c" => sl("lang")->tr("Disk"),
                "d" => sl("lang")->tr("CD-ROM"),
                "n" => sl("lang")->tr("Network"),
            ];
            if(version_compare($this->api()->getVersion(), "6.3", '>=')){
                $cdrom = $this->vm()->cdrom();
                $nd = $this->vm()->getNetworkDevices($this->configuration()->getBridge());
                $options                             = [
                    0   => sl("lang")->tr("None"),
                    $this->vm()->getMasterHardDisk()->getId() => sl("lang")->tr("Disk"),
                ];
                if($cdrom['bus']){
                    $options[$cdrom['bus']] = sl("lang")->tr("CD-ROM");
                }
                if($nd[0] instanceof  NetworkDeviceKvm){
                    $options[$nd[0]->getId()] = sl("lang")->tr("Network");
                }
            }
            $this->availableValues['bootOrder0'] = $options;
            $this->availableValues['bootOrder1'] = $options;
            $this->availableValues['bootOrder2'] = $options;
            //sshkeys
            $this->data['sshkeys'] = rawurldecode($this->vm()->config()['sshkeys']);
        }
        else
        {
            if ($this->vm() instanceof Lxc)
            {
                //hostname
                $this->data['hostname'] = $this->vm()->config()['hostname'];
            }
        }

    }

    public function update()
    {
        if ($this->vm() instanceof Kvm)
        {
            //Hostname
            $this->vm()->updateConfig(["name" => $this->formData['hostname']]);
            //iso
            if ($this->vm()->cdrom())
            {
                $this->vm()->updateCdrom($this->formData['iso']);
            }
            //Boot order
            $bootOrder = null;
            $order = [];
            for ($i = 0; $i <= 2; $i++)
            {
                if ($this->formData['bootOrder' . $i])
                {
                    $bootOrder .= $this->formData['bootOrder' . $i];
                    $order[] = $this->formData['bootOrder' . $i];
                }
            }
            if(version_compare($this->api()->getVersion(), "6.3", '>=') && !empty($order)){

                //order=scsi0;ide0;ide1;net0
                $this->vm()->updateConfig(['boot' => "order=".implode(";", $order)]);
            }else{
                $this->vm()->changeBootOrder($bootOrder);
            }

            //sshkeys
            if($this->configuration()->isPermissionSshkeys()){
                if ($this->formData['sshkeys'])
                {
                    $this->vm()->updateConfig(["sshkeys" => rawurlencode($this->formData['sshkeys'])]);
                } else if($this->vm()->config()['sshkeys'])
                {
                    $this->vm()->deleteConfig('sshkeys');
                }
                if (isset($this->getWhmcsParamByKey("customfields")['sshkeys']))
                {
                    $this->customFieldUpdate('sshkeys', $this->formData['sshkeys']);
                }
            }
        }
        else
        {
            if ($this->vm() instanceof Lxc)
            {
                //Hostname
                $this->vm()->updateConfig(["hostname" => $this->formData['hostname']]);
            }
        }
        if( $this->hosting()->domain != $this->formData['hostname'] ){
            $this->hosting()->update(['domain' => $this->formData['hostname'] ]);
        }

        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('Service information has been changed')
            ->addRefreshTargetId('serviceInformationDataTable');

    }

}