<?php

/* * ********************************************************************
 * ProxmoxAddon product developed. (Oct 4, 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\Servers\Pages;

use MGProvision\Proxmox\v2 as proxmox;
use ModulesGarden\ProxmoxAddon as main;
use WHMCS\Database\Capsule as DB;
use WHMCS\Service\Service;

/**
 * Description of ServerResources
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
trait ServerResources
{

    use main\App\Services\BaseService;
    use main\Core\UI\Traits\RequestObjectHandler;
    protected $errors = [];
    protected $hostingStatus = ["Active"];
    private $ramAssigned = 0;
    private $ramTotal = 0;
    private $ramFree = 0;
    private $ramSuspended = 0;

    public function getHostingStatus()
    {
        return $this->hostingStatus;
    }

    public function setHostingStatus($hostingStatus)
    {
        $this->hostingStatus = $hostingStatus;
        return $this;
    }

    public function ramAssignedToSring()
    {
        return main\App\Libs\Format::convertBytes($this->ramAssigned);
    }

    public function ramTotalToSring()
    {
        return main\App\Libs\Format::convertBytes($this->ramTotal);
    }

    public function ramFreeToSring()
    {
        return main\App\Libs\Format::convertBytes($this->ramFree);
    }

    public function ramSuspendedToSring()
    {
        return main\App\Libs\Format::convertBytes($this->ramSuspended);
    }

    protected function ramDetails()
    {
        $nodeRepository = new proxmox\repository\NodeRepository();
        $serverAssignedIps = $this->getServer()->assignedips;
        $serverAssignedIps = preg_replace('/\s+/', '', $serverAssignedIps);
        $serverAssignedIps = explode(PHP_EOL, $serverAssignedIps);
        $privateIp = current($serverAssignedIps);
        $serverIp =  $privateIp ?  $privateIp :  $this->getServer()->ipaddress;
            $node           = $nodeRepository->findWithHostOrIp($this->getServer()->hostname, $serverIp );
        //Get hosting for this server with status active and suspended
        foreach (Service::where('server', $this->getServerId())->whereIn('domainstatus', $this->hostingStatus)->get() as $hosting)
        {
            try
            {
                if ($this->getServer()->type == "proxmoxVPS")
                {
                    $customFields = new \stdClass;
                    foreach ($hosting->customFieldValues as $cf)
                    {
                        if ($cf->value && preg_match("/node/", $cf->customField->fieldName))
                        {
                            $customFields->node = $cf->value;
                        }
                        if ($cf->value && preg_match("/vmid/", $cf->customField->fieldName))
                        {
                            $customFields->vmid = $cf->value;
                        }
                    }
                    if (!empty($customFields->vmid) && !empty($customFields->node) && $node->getNode() == $customFields->node)
                    {
                        $customFields->type = DB::table('ProxmoxAddon_ProductConfiguration')
                            ->where('product_id', $hosting->packageId)
                            ->where("setting", "virtualization")
                            ->value("value");
                        $customFields->type = \json_decode(strtolower($customFields->type), true);
                        $customFields->virtualization =  $customFields->type;
                        $vm = proxmox\Factory::vm($customFields);
                        $this->vmDetails($vm, $hosting);
                    }
                }
                else
                {
                    if ($this->getServer()->type == "ProxmoxCloudVps")
                    {
                        $query = DB::table('ProxmoxAddon_Vm')
                            ->where('hosting_id', $hosting->id)
                            ->where('node', $node->getNode())
                            ->select('node', 'vmid', 'virtualization', 'node');
                        foreach ($query->get() as $vserver)
                        {
                            $vm = proxmox\Factory::vm($vserver);
                            $this->vmDetails($vm, $hosting);
                        }
                    }
                }
                $this->ramTotal = $node->getStatus()['memory']['total'];
                $this->ramFree  = $this->ramTotal - $this->ramAssigned;
            }
            catch (\Exception $ex)
            {
                if( main\App\Models\Job::ofHostingId($hosting->id)->waiting()->count()){
                    continue;
                }
                $this->errors[] = sprintf("Hosting #%s %s", $hosting->id, $ex->getMessage() );
            }
        }
    }

    private function vmDetails(proxmox\interfaces\VmInterface $vm, $hosting)
    {
        $stat = $vm->status();
        if (!empty($stats['maxmem']))
        {
            $memory = $stats['maxmem'];
        }
        else
        {
            $config = $vm->config();
            $memory = (int)$config['memory'] * 1048576;
        }

        if ($hosting->domainStatus == "Active")
        {
            $this->ramAssigned += $memory;
        }
        else
        {
            if ($hosting->domainStatus == "Suspended")
            {
                $this->ramSuspended += $memory;
            }
        }
    }
}
