<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (26.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\ServiceInformation\Pages;

use MGProvision\Proxmox\v2\models\Kvm;
use MGProvision\Proxmox\v2\models\Lxc;
use MGProvision\Proxmox\v2\models\NetworkDeviceKvm;
use MGProvision\Proxmox\v2\models\NetworkDeviceLxc;
use ModulesGarden\ProxmoxAddon\App\Libs\Format;
use ModulesGarden\ProxmoxAddon\App\Models\KeyPair;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\UrlService;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Home\Buttons\RedirectButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\ServiceInformation\Buttons\SshPrivateKeyDownloadButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\ServiceInformation\Buttons\UpdateButton;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Builder\BaseContainer;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AdminArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AjaxElementInterface;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\RawDataJsonResponse;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\isAdmin;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;

class ServiceInformation extends BaseContainer implements ClientArea, AdminArea, AjaxElementInterface
{

    use ProductService;
    use ApiService;

    protected $id = 'serviceInformationDataTable';
    protected $title = 'serviceInformationDataTable';
    protected $vueComponent = true;
    protected $defaultVueComponentName = 'mg-serviceInformationDataTable';

    public function initContent()
    {
        $this->addClass('lu-text-left')
            ->addClass('lu-col-md-12');

        //Update
        $this->addButton(new UpdateButton());
        if ($this->configuration()->isLxc() && KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->count())
        {
            $vmId = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel()->id;
            /**
             * @deprecated
            $keyPairs = KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->ofVmId($vmId)
            ->first();
            //Private Key
            $deletePrivateKey = $this->configuration()->isSshDeletePrivateKey();
            if (!$deletePrivateKey && $keyPairs && $keyPairs->isPrivate())
            {
            $rd = new RedirectButton("sshPrivateKeyDownloadButton");
            $rd->replaceClasses(['lu-btn lu-btn--sm lu-btn lu-btn--link lu-btn--icon lu-btn--plain lu-btn--default']);
            $rd->setIcon('lu-zmdi lu-zmdi-shield-check');
            $rd->setHref($urlService->getUrl("sshKey", "sshPrivateKeyDownload",['vm'=> $vmId]));
            $this->addButton($rd);
            }
            else
            {
            if ($deletePrivateKey && $keyPairs && $keyPairs->isPrivate())
            {
            $this->addButton(new SshPrivateKeyDownloadButton());
            }
            }
             */

            //URL
            $urlService = new UrlService();
            //Public Key
            $rd = new RedirectButton("sshPublicKeyDownloadButton");
            $rd->replaceClasses(['lu-btn lu-btn--sm lu-btn lu-btn--link lu-btn--icon lu-btn--plain lu-btn--default']);
            $rd->setIcon('lu-zmdi lu-zmdi-shield-security');
            $rd->setHref($urlService->getUrl("sshKey", "sshPublicKeyDownload",['vm'=> $vmId]));
            $this->addButton($rd);


        }
    }

    public function returnAjaxData()
    {
        //Close session, it speed up page loading
        session_write_close();

        $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
        $vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
        $vars                = [];
        //Status
        $status         =  $vm->status();
        $vars['status'] = [
            "uptime" => Utility::uptime($status['uptime']),
            'cpu'    => Utility::cpuUsage($status['cpu']),
            'cpus' => (int) $status['cpus']
        ];
        switch ($status['status'])
        {
            case 'running':
                $vars['status']['status'] = '<span class="lu-label lu-label--success lu-label--status">' . sl('lang')->abtr($status['status']) . '</span>';
                break;
            case 'stoped':
                $vars['status']['status'] = '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->abtr($status['status']) . '</span>';
            default:
                $vars['status']['status'] = '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->abtr($status['status']) . '</span>';
        }
        //Memory
        $vars['status']['memPercent'] = (int) round($status['mem'] / $status['maxmem'] * 100);
        $vars['status']['maxmem']     = Format::convertBytes($status['maxmem']);
        $vars['status']['mem']        = Format::convertBytes($status['mem']);
        if ( $vm instanceof Lxc)
        {
            //SWAP
            $vars['status']['swapPercent'] = (int) round($status['swap'] / $status['maxswap'] * 100);
            $vars['status']['swap']        = Format::convertBytes($status['swap']);
            $vars['status']['maxswap']     = Format::convertBytes($status['maxswap']);
            //Disk
            $vars['status']['diskPercent'] = (int) round($status['disk'] / $status['maxdisk'] * 100);
            $vars['status']['disk']        = Format::convertBytes($status['disk']);
            $vars['status']['maxdisk']     = Format::convertBytes($status['maxdisk']);
            $vars['status']['diskwrite']   = Format::convertBytes($status['diskwrite']);
            //Key Pairs
            if (KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->count())
            {
                $keyPairs                    = KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->first();
                $vars['keyPairs']['public']  = $keyPairs->isPrivate();
                $vars['keyPairs']['private'] = $keyPairs->isPrivate();
            }
        }
        if ($status['balloon_min'])
        {
            $vars['status']['balloon_min'] = Format::convertBytes($status['balloon_min']);
        }
        //Config
        $vars['config'] = [
            "name" =>  $vm->config()['name'] ?  $vm->config()['name'] :  $vm->config()['hostname']
        ];
        if (isAdmin())
        {
            $vars['node'] =  $vm->getNode();
        }
        $vars['virtualization'] =  $vm->getVirtualization();
        //NetworkRate
        /** @var NetworkDeviceKvm|NetworkDeviceLxc $networkDevice */
        $networkDevice =  $vm->getNetworkDevices($this->configuration()->getBridge())[0];
        if ($networkDevice && $networkDevice->getRate())
        {
            $vars['networkRate'] = "{$networkDevice->getRate()} MB/s ({$networkDevice->getRateMbps()} Mbps)";
        }
        //KVM
        if ( $vm instanceof Kvm)
        {
            //CD-ROM
            $vars['cdrom'] =  $vm->getIso();
            //Boot order
            $vars['bootOrder'] = [];
            foreach ( $vm->getBootOrder() as $device)
            {
                $vars['bootOrder'][] = sl("lang")->tr("bootOrder", $device);
            }
            $vars['bootOrder'] = implode(", ", $vars['bootOrder']);
            //SSH Public Key
            $vars['sshkeysName'] =  $vm->sshkeysName();
        }
        //OS Info
        if (isAdmin() &&  $vm->config()['agent'] == 1)
        {
            try
            {
                $vars['osinfo']                  =  $vm->agent()->getOsinfo()['result'];
                $vars['osinfo']['kernelrelease'] = $vars['osinfo']['kernel-release'];
                $vars['hostname']                =  $vm->agent()->getHostname()['result']['host-name'];
            }
            catch (\Exception $ex)
            {
                $vars['quemuAgent'] = $ex->getMessage();
            }
        }
        if (isAdmin() &&  $vm instanceof  Lxc)
        {
            $features =   $vm->config()['features'];
            $vars['features'] = $features ? $features : "-";
        }
        $vars['created_at'] =  fromMySQLDate($vmModel->created_at);
        $vars['description'] = $vm->config()['description'] ? $vm->config()['description'] : '-';

        return (new RawDataJsonResponse(['data' => $vars]));
    }


}