<?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\Vms\Pages;

use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Decorators\OsTemplateDecorator;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\CreateButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\DeleteButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\ConsoleButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\ManageButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\ImportButton;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Vms\Buttons\MigrateButton;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\AdminArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Buttons\ButtonRedirect;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\DataTable\DataProviders\Providers\QueryDataProvider;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\DataTable\DataTable;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\BuildUrl;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\isAdmin;
use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;


class VmsDataTable extends DataTable implements ClientArea, AdminArea
{

    use ApiService;
    use ProductService;

    protected $id = 'vmsDataTable';
    protected $title = 'vmsDataTable';
    protected $searchable = false;
    protected $tableLength = "100";
    protected $urlService;

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

        $isAdmin = isAdmin();
        //create
        $resurceManager = new ResourceManager();
        if(!$isAdmin){
            $createButton = new ButtonRedirect('createVmButton');
            $createButton->setShowTitle();
            $url ="clientarea.php?action=productdetails&id={$this->getWhmcsParamByKey('serviceid')}&modop=custom&a=management&mg-page=vm&mg-action=create";
            $createButton->setRawUrl($url);
            $createButton->setIcon('lu-zmdi lu-zmdi-plus');
            $createButton->replaceClasses(['lu-btn lu-btn--primary']);
            $createButton->addClass("pmCreateVirtualMachineButton");
            //deaktivate createVM Button in case of lack of ressources
            if($resurceManager->disk()->free() < $resurceManager->disk()->getMin() || $resurceManager->vcpus()->free() < $resurceManager->vcpus()->getMin() || $resurceManager->memory()->free() < $resurceManager->memory()->getMin()) {
                $createButton->addClass("disabled");
            }
            $this->addTitleButton($createButton);
        }
        //import
        if($isAdmin){
            $this->addButton(new ImportButton());
            //migrate
            $this->addActionButton(new MigrateButton());
        }
        if (!isAdmin() && $this->configuration()->isPermissionNovnc()){
            //console
            $this->addActionButton(new ConsoleButton());
        }
        if(!$isAdmin){
            //edit
            $this->addActionButton(new ManageButton());
        }
        //delete
        $this->addActionButton(new DeleteButton());
    }

    protected function loadHtml()
    {
        if(isAdmin()){
            $this->addColumn((new Column('vmid')));
        }
        $this->addColumn((new Column('name')))
            ->addColumn((new Column('status')))
            ->addColumn((new Column('vcpus')))
            ->addColumn((new Column('memory')))
            ->addColumn((new Column('disk')))
            ->addColumn((new Column('osTemplate')));
    }


    public function replaceFieldStatus($key, $row)
    {

        try{
            //current
            if($row->vmid==0){
                return '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->abtr( "Build") . '</span>';
            }
            $vmModel = VmModel::ofId($row->id)->firstOrFail();
            $this->api();
            $status = (new VmFactory())->fromVmModel($vmModel)->status()['status'];
            if ($status=='running')
            {
                return '<span class="lu-label lu-label--success lu-label--status">' . sl('lang')->abtr($status) . '</span>';
            }
            return '<span class="lu-label lu-label--danger lu-label--status">' . sl('lang')->abtr($status) . '</span>';
        }catch (\Exception $ex){
            return '<span class="lu-label lu-label--danger lu-label--status">' . $ex->getMessage() . '</span>';
        }


    }

    public function replaceFieldOsTemplate($key, $row)
    {
        $json = \json_decode($row->data, true);
        if(!$json['osTemplate'] || $json['osTemplate'] =='installationFromIso'){
            return sl('lang')->abtr('template', "Installation From ISO Image");
        }
        $decorator = new OsTemplateDecorator($json['osTemplate']);
        return sl('lang')->abtr('template', $decorator->toFriendlyName());
    }

    public function replaceFieldDisk($key, $row)
    {
        return sprintf(" %s GB", $row->disk + $row->disks);
    }

    public function replaceFieldMemory($key, $row)
    {
        return sprintf(" %s MB", $row->memory);
    }

    protected function loadData()
    {
        $query    = VmModel::select("id", "name", "vcpus", "memory", "disk","disks", "vmid","data")
            ->ofHostingId($this->getWhmcsParamByKey('serviceid'))
            ->notTemplate()
            ->getQuery();
        $dataProv = new QueryDataProvider();
        $dataProv->setDefaultSorting("name", 'ASC');
        $dataProv->setData($query);
        $this->setDataProvider($dataProv);
    }

    public function isViewFooter()
    {
        return false;
    }

    public function isViewTopBody()
    {
        return isAdmin();
    }

}