<?php

/* * ********************************************************************
 * ProxmoxVPS product developed. (Apr 19, 2019)
 * *
 *
 *  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\Cron;

use MGProvision\Proxmox\v2\VmFactory;
use ModulesGarden\ProxmoxAddon\App\Models\RrdData;
use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
use ModulesGarden\ProxmoxAddon\App\Models\Whmcs\Hosting;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\Core\CommandLine\Command;
use ModulesGarden\ProxmoxAddon\Core\CommandLine\Hypervisor;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Server;
use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;

/**
 * Description of Users
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class RrdDataCommand extends Command
{
    use WhmcsParams;
    use \ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
    use ApiService;

    /**
     * Command name
     * @var string
     */
    protected $name = 'rrddata';

    /**
     * Command description
     * @var string
     */
    protected $description = 'Updating RRD Data';

    /**
     * Command help text
     * @var string
     */
    protected $help = '';

    protected function process(InputInterface $input, OutputInterface $output, SymfonyStyle $io)
    {
        $io->title('Update RRD Data: Starting');
        if (!function_exists('ModuleBuildParams'))
        {
            require_once ROOTDIR . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . "modulefunctions.php";
        }
        //Update hosting bandwidth
        $h        = (new Hosting())->getTable();
        $s        = (new Server())->getTable();
        $hostings = Hosting::select("{$h}.id", "{$h}.packageid", "{$h}.lastupdate", "{$h}.bwusage", "{$h}.bwlimit", "{$h}.regdate")
            ->rightJoin($s, "{$h}.server", '=', "{$s}.id")
            ->where("{$h}.domainstatus", "Active")
            ->whereIn("{$s}.type", [ "ProxmoxCloudVps"])
            ->orderBy("{$h}.server");
        $i        = 0;
        /**
         * @var Hosting $hosting
         */
        foreach ($hostings->get() as $hosting)
        {
            $i++;
            $output->writeln(sprintf("Synchronize hosting: %s", $hosting->id));
            try
            {
                $params = \ModuleBuildParams($hosting->id);
                sl("whmcsParams")->setParams($params);
                unset($this->vm, $this->api, $this->configuration, $this->productId, $this->hostingId);
                $this->api();
                RrdData::ofHostingId($hosting->id)->olderThanDayAgo()->delete();
                if ($params['moduletype'] == "ProxmoxCloudVps"){
                    $vservers = VmModel::ofHostingId($hosting->id);
                    foreach ($vservers->get() as $vserver)
                    {
                        $vm = (new VmFactory())->fromVmModel($vserver);
                        $rrData    = $vm->rrdData(["timeframe" => "hour", "cf" => "AVERAGE"]);
                        foreach ($rrData as $k => $rrd)
                        {
                            $rrdModel = new RrdData();
                            $rrdModel->fill($rrd);
                            $rrdModel->time =  date("Y-m-d H:i:s", $rrd['time']);
                            $rrdModel->hosting_id = $hosting->id;
                            $rrdModel->vm_id = $vserver->id;
                            $rrdModel->save();
                        }
                    }
                    $output->writeln(sprintf("Hosting: %s has been synchronized", $hosting->id));
                }

            }
            catch (\Exception $ex)
            {
                $msg = $ex->getMessage();
                if ($hosting)
                {
                    $msg = sprintf("Hosting Id #%s, %s", $hosting->id, $ex->getMessage());
                }
                $io->error($msg);
            }
            (new Hypervisor($this->getName(), $input->getOptions()))
                ->ping();
        }
        $output->writeln("");
        $io->success([
            sprintf("Synchronize hostings: %s Entries Processed.", $i),
            "Update RRD Data: Done"
        ]);
    }



}
