<?php

/* * ********************************************************************
 * WordPress Manager product developed. (Feb 5, 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\Pages;

use MGProvision\Proxmox\v2 as proxmox;
use ModulesGarden\ProxmoxAddon as main;
use ModulesGarden\ProxmoxAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\DataTable\Column;
use ModulesGarden\ProxmoxAddon\Core\UI\Widget\RawDataTable\RawDataTable;
use \ModulesGarden\ProxmoxAddon\App\UI\Cluster\Buttons\UpdateButton;

/**
 * Description of PluginInstalled
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class ClusterDataTable extends RawDataTable implements AdminArea
{

    use main\App\Services\BaseService;
    protected $id    = 'cluster';
    protected $name  = 'clusterName';
    protected $title = 'clusterTitle';

    public function isRawTitle()
    {
        return false;
    }

    public function initContent()
    {
        //Update
        $this->addActionButton(new UpdateButton);
        $rd = new main\Core\UI\Widget\Buttons\ButtonRedirect();
        $rd->setRawUrl('addonmodules.php?module=proxmoxAddon&mg-page=home&mg-action=nodeDetail&serverId=' . $this->getRequestValue('id'))
            ->setIcon('lu-btn__icon lu-zmdi lu-zmdi-info-outline')
            ->setRedirectParams(['id' => ':id']);
        $this->addActionButton($rd);
        try
        {
            $this->setServerId($this->getRequestValue('id'))->getApi();
        }
        catch (\Exception $ex)
        {
            $this->setInternalAlertMessage($ex->getMessage())
                ->setInternalAlertMessageType('danger');
        }
    }

    public function replaceFieldUptime($key, $row)
    {
        return main\App\Libs\Format::uptime($row['status']['uptime']);
    }

    public function replaceFieldCpuUsage($key, $row)
    {
        $cpu = $row['status']['cpu'] ? round($row['status']['cpu'] * 100, 2) . " %" : "0 %";
        return $cpu . ' of  ' . $row['status']['cpuinfo']['cpus'] . ' CPU(s)';
    }

    public function replaceFieldSwap($key, $row)
    {
        return main\App\Libs\Format::convertBytes($row['status']['swap']['used']) . ' / ' . main\App\Libs\Format::convertBytes($row['status']['swap']['total']);
    }

    public function replaceFieldMemory($key, $row)
    {
        return main\App\Libs\Format::convertBytes($row['status']['memory']['used']) . ' / ' . main\App\Libs\Format::convertBytes($row['status']['memory']['total']);
    }

    public function replaceFieldRootfs($key, $row)
    {
        return main\App\Libs\Format::convertBytes($row['status']['rootfs']['used']) . ' / ' . main\App\Libs\Format::convertBytes($row['status']['rootfs']['total']);
    }

    protected function loadHtml()
    {
        $this->addColumn((new Column('node'))->setSearchable(true, Column::TYPE_STRING)->setOrderable('ASC'))
            ->addColumn((new Column('uptime'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('vmsLimit'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('cpuLimit'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('diskLimit'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('ramLimit'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('cpuUsage'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('swap'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('memory'))->setSearchable(true, Column::TYPE_STRING)->setOrderable())
            ->addColumn((new Column('rootfs'))->setSearchable(true, Column::TYPE_STRING)->setOrderable());
    }

    protected function loadData()
    {
        $this->loadRequestObj()->setServerId($this->getRequestValue('id'))->getApi()->setInstance();
        $dataProv       = new main\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider();
        $nodeRepository = new proxmox\repository\NodeRepository();
        $data           = [];
        $loadBalancer = new main\App\Services\LoadBalancerService($this->getRequestValue('id'));
        $loadBalancer->setApi($this->getApi());
        foreach ($nodeRepository->fetch() as $node)
        {
            $loadBalancer->findByNode($node->getNode(),false);
            $resurces = $loadBalancer->getNodesResurces()[0];
            /* @var $node proxmox\models\Node */
            $data[] = [
                "id" => $node->getNode(),
                "node" => $node->getNode(),
                "status" => $node->getStatus(),
                "vmsLimit" => sprintf("%s / %s" ,(int)$resurces['vmsUsed'] , $resurces['vmsMax'] ? $resurces['vmsMax']  : '-'  ) ,
                "cpuLimit" => sprintf("%s / %s" ,(int)$resurces['cpuUsed'] , $resurces['cpuMax'] ? $resurces['cpuMax']  : '-'  ) ,
                "diskLimit" => sprintf("%s / %s" ,main\App\Libs\Format::convertBytes((int)$resurces['diskUsed'] ), main\App\Libs\Format::convertBytes($resurces['diskMax'] ) ) ,
                "ramLimit" => sprintf("%s / %s" ,main\App\Libs\Format::convertBytes((int)$resurces['ramUsed'] ), main\App\Libs\Format::convertBytes($resurces['ramMax']  )) ,

            ];
        }
        $dataProv->setDefaultSorting("node", 'ASC');
        $dataProv->setData((array) $data);
        $this->setDataProvider($dataProv);
    }
}
