<?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\ProxmoxVps\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\Utility;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UrlService;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Home\Buttons\RedirectButton;
use ModulesGarden\Servers\ProxmoxVps\App\UI\ServiceInformation\Buttons\SshPrivateKeyDownloadButton;
use ModulesGarden\Servers\ProxmoxVps\App\UI\ServiceInformation\Buttons\UpdateButton;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Builder\BaseContainer;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\AdminArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\AjaxElementInterface;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\ResponseTemplates\RawDataJsonResponse;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\isAdmin;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\sl;
use ModulesGarden\Servers\ProxmoxVps\App\Enum\ConfigurableOption;

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');

        //Update
        $this->addButton(new UpdateButton());
        if ($this->configuration()->isLxc() && KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->count())
        {
            $keyPairs = KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->first();
            //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("home", "sshPublicKeyDownload"));
            $this->addButton($rd);
            //Private Key
            $deletePrivateKey = $this->configuration()->isSshDeletePrivateKey();
            if (!$deletePrivateKey && $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("home", "sshPrivateKeyDownload"));
                $this->addButton($rd);
            }
            else
            {
                if ($deletePrivateKey && $keyPairs->isPrivate())
                {
                    $this->addButton(new SshPrivateKeyDownloadButton());
                }
            }
        }
    }

    public function returnAjaxData()
    {
        $vars                = [];
        //Status
        $status         = $this->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')->tr($status['status']) . '</span>';
                break;
            case 'stoped':
                $vars['status']['status'] = '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->tr($status['status']) . '</span>';
            default:
                $vars['status']['status'] = '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->tr($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 ($this->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" => $this->vm()->config()['name'] ? $this->vm()->config()['name'] : $this->vm()->config()['hostname']
        ];
        if (isAdmin())
        {
            $vars['node'] = $this->vm()->getNode();
        }
        $vars['virtualization'] = $this->vm()->getVirtualization();
        // Default configuration option
        if (!$this->isWhmcsConfigOption(ConfigurableOption::IPV4) && $this->configuration()->getIpv4())
        {
            $vars['ipAddresses'] = $this->configuration()->getIpv4();
        }
        //BackupMaxFiles
        if (!$this->isWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES) && $this->configuration()->getBackupMaxFiles())
        {
            $vars['backupsFilesLimit'] = $this->configuration()->getBackupMaxFiles();
            if($this->configuration()->getBackupMaxFiles() =="-1"){
                $vars['backupsFilesLimit'] = sl('lang')->abtr("Unlimited");
            }
        }
        //NetworkRate
        /** @var NetworkDeviceKvm|NetworkDeviceLxc $networkDevice */
        $networkDevice = $this->vm()->getNetworkDevices($this->configuration()->getBridge())[0];
        if ($networkDevice && $networkDevice->getRate())
        {
            $vars['networkRate'] = "{$networkDevice->getRate()} MB/s ({$networkDevice->getRateMbps()} Mbps)";
        }
        //KVM
        if ($this->vm() instanceof Kvm)
        {
            //CD-ROM
            $vars['cdrom'] = $this->vm()->getIso();
            //Boot order
            $vars['bootOrder'] = [];
            foreach ($this->vm()->getBootOrder() as $device)
            {
                $vars['bootOrder'][] = sl("lang")->tr("bootOrder", $device);
            }
            $vars['bootOrder'] = implode(", ", $vars['bootOrder']);
            //SSH Public Key
            $vars['sshkeysName'] = $this->vm()->sshkeysName();
        }
        //OS Info
        if (isAdmin() && $this->vm()->config()['agent'] == 1)
        {
            try
            {
                $vars['osinfo']                  = $this->vm()->agent()->getOsinfo()['result'];
                $vars['osinfo']['kernelrelease'] = $vars['osinfo']['kernel-release'];
                $vars['hostname']                = $this->vm()->agent()->getHostname()['result']['host-name'];
            }
            catch (\Exception $ex)
            {
                $vars['quemuAgent'] = $ex->getMessage();
            }
        }
        if (isAdmin() && $this->vm() instanceof  Lxc)
        {
            $features =  $this->vm()->config()['features'];
            $vars['features'] = $features ? $features : "-";
        }
        return (new RawDataJsonResponse(['data' => $vars]));
    }


}