<?php

require_once APPPATH . 'libraries/Cf_REST_Controller.php';

class Vitals extends Cf_REST_Controller
{


    function __construct()
    {
        parent::__construct();
        $this->load->model('vitals_model');
        $this->load->model('vitals_rest_model');
        $this->load->model('host_model');

        $this->vitals_rest_model->setRestClient($this->getRestClient());
    }

    function node_vitals_get()
    {

        $username = $this->session->userdata('username');
        $this->config->load('vitals');
        $vitalsMaxNode = $this->config->item('vitals_max_nodes');
        $incList = $this->param_includes();

        $data = array();
        $obs = $this->param('obs', TRUE) ? $this->param('obs', TRUE) : 'loadavg';
        $sort = $this->param('sort', TRUE) ? $this->param('sort', TRUE) : 'last-measured';
        $sortOrder = $this->param('sortOrder', TRUE) ? strtolower($this->param('sortOrder', TRUE)) : 'desc';
        $sortBool = ($sortOrder == 'asc') ? false : true;
        try
        {
            $listOfHostJson = cfpr_hosts_sorted_by_last_vital_value($username, $obs, $incList, array(), $sortBool, $vitalsMaxNode, 1);
            $listOfHost = json_decode($listOfHostJson, true);
            htmlSpecialCharsArrayEncode($listOfHost);

            foreach ($listOfHost as $index => $host)
            {
                $data[$index]['meta']['hostkey'] = $host['hostkey'];
                $data[$index]['meta']['hostname'] = $host['hostname'];

                $data[$index]['meta']['lastUpdated'] = $host['lastUpdate'];
                $data[$index]['meta']['average'] = 0;
                $data[$index]['meta']['lastValue'] =  empty($host['lastValue'])  ? 0 : $host['lastValue'];
                $data[$index]['perfdata'] = array();
            }
            $this->respond(200, json_encode($data));
            return;

        }
        catch (Exception $e)
        {
            $errorMessage = $e->getMessage();
            log_message('error',"Failed loading vitals value with message: ".$errorMessage);
            $this->respond_internal_error(json_encode($errorMessage));
            return;
        }

    }

    function host_vital_performance_data_get()
    {

        $this->load->model('vitals_rest_model');
        $this->vitals_rest_model->setRestClient($this->getRestClient());
        $username = $this->session->userdata('username');
        $this->config->load('vitals');

        $data = array();
        $obs = $this->param('obs', TRUE) ? $this->param('obs', TRUE) : 'loadavg';
        $timeFrame = $this->param('timeFrame', TRUE) ? $this->param('timeFrame', TRUE) : 6;
        $key = $this->param('hostkey', TRUE) ? $this->param('hostkey', TRUE) : null;
        $lu = $this->param('lastUpdated', TRUE) ? $this->param('lastUpdated', TRUE) : null;
        try
        {
            if ($lu)
            {
                $lastMeasured = $this->vitals_rest_model->getVitalsMagnifiedViewJson($username, $key, $obs, $lu, $timeFrame);
            }
            else
            {
                // if no last updated date dont fetch anything
                $lastMeasured = null;
            }
        }
        catch (Exception $e)
        {
            // we are getting exception
            // just initialize no data
            $lastMeasured = null;
        }

        $this->respond(200, $lastMeasured);
    }

    function host_vitals_get()
    {
        $username = $this->session->userdata('username');


        $incList = $this->param_includes();
        $listOfHost = $this->host_model->getHostListByContext($incList, array());
        $obs = $this->param('obs', TRUE) ? $this->param('obs', TRUE) : null;
        $timeFrame = $this->param('timeFrame', TRUE) ? $this->param('timeFrame', TRUE) : 6;
        $hourAgo = $timeFrame;
        $vitalList = array();
        if (!empty($listOfHost))
        {
            $host = $listOfHost[0];
            $hostkey = $host['id'];
            $vitalListData = $this->vitals_rest_model->getVitalsList($username, $hostkey);
            $vitalList = array();
            $vitalList['obs'] = $vitalListData['data'];
            $vitalList['hostkey'] = $hostkey;
            $vitalList['lastUpdated'] = $vitalListData['meta']['timestamp'];
            krsort($vitalList['obs']);

            if ($obs === null)
            {
                foreach ($vitalList['obs'] as $index => $vitals)
                {
                    $vitalId = $vitals['id'];
                    $lu = $vitals['timestamp'];
                    $vitalList['obs'][$index]['perfdata'] = array(); // $this->vitals_rest_model->getVitalsMagnifiedViewJson($username, $hostkey, $vitalId, $lu, $hourAgo);
                }
            }
            else
            {

                // we are only requesting one particular vital sign
                $found = false;
                foreach ($vitalList['obs'] as $index => $vitals)
                {
                    $vitalId = $vitals['id'];
                    if ($vitalId === $obs)
                    {
                        $lu = $vitals['timestamp'];
                        $vitalList['obs'][$index]['perfdata'] = array(); //$this->vitals_rest_model->getVitalsMagnifiedViewJson($username, $hostkey, $vitalId, $lu, $hourAgo);
                        $found = true;
                        // remove other elements from $vitalList array
                        $tempObs = $vitalList['obs'][$index];
                        $vitalList['obs'] = array($tempObs); // overwrite


                        break;
                    }
                }
                if (!$found)
                {
                    // we did not find any vitals for given parameters
                    // return the first vital parameter
                    foreach ($vitalList['obs'] as $index => $vitals)
                    {
                        $vitalId = $vitals['id'];
                        $lu = $vitals['timestamp'];
                        $tempObs = $vitalList['obs'][$index];
                        $vitalList['obs'] = array($tempObs); // overwrite
                        break;
                    }
                }
            }
        }
        $this->respond(200, json_encode($vitalList));
    }

    function config_vitals_get()
    {
        $this->config->load('vitals', TRUE);
        $vitalsArray = array();
        $vitalsArray['vitals'] = $this->config->item('vitals', 'vitals');
        $vitalsArray['vitals-sort-by'] = $this->config->item('vitals-sort-by', 'vitals');
        $this->respond(200, json_encode($vitalsArray));
    }

    function vital_panel_menu_get()
    {
        $this->config->load('vitals', TRUE);
        $vitalsArray = array();
        $vitalsArray['vitals'] = $this->config->item('vitals', 'vitals');
        $vitalsArray['vitals_sort_by'] = $this->config->item('vitals-sort-by', 'vitals');
        $vitalsArray['vitals_sort_hour'] = $this->config->item('vitals-sort-hour', 'vitals');

        $html = $this->load->view('vitals/vitals-head-panel', $vitalsArray, TRUE);
        $this->respond(200, $html);
    }

    function vital_panel_menu_host_get()
    {
        $this->config->load('vitals', TRUE);
        $username = $this->session->userdata('username');
        $incList = $this->param_includes();
        $listOfHost = $this->host_model->getHostListByContext($incList, array());
        $obs = $this->param('obs', TRUE) ? $this->param('obs', TRUE) : null;
        $vitalList = array();
        if (!empty($listOfHost))
        {
            $host = $listOfHost[0];
            $hostkey = $host['id'];
            $vitalListData = $this->vitals_rest_model->getVitalsList($username, $hostkey);
            $vitalList['obs'] = $vitalListData['data'];
            krsort($vitalList['obs']);
        }
        $vitals_sort_hour = $this->config->item('vitals-sort-hour', 'vitals');
        $data = array('vitalList' => $vitalList, 'selectedObs' => $obs, 'vitals_sort_hour' => $vitals_sort_hour);

        $html = $this->load->view('vitals/vitals-head-panel-host', $data, TRUE);
        $this->respond(200, $html);
    }

    function vital_detail_view_get($hostkey = null, $obs = null)
    {

        $username = $this->session->userdata('username');
        if ($hostkey && $obs)
        {
            $data = array(
                'hostKey' => $hostkey,
                'obs' => $obs
            );
            $hostInfo = $this->host_model->getHostInfo($username, $hostkey);
            $data['hostname'] = $hostInfo["hostname"];
            $data['ip'] = $hostInfo["ip"];

            $convertData = $this->vitals_rest_model->getVitalsList($username, $hostkey);
            if (is_array($convertData) && array_key_exists('data', $convertData) && !empty($convertData['data']))
            {

                foreach ($convertData['data'] as $v)
                {
                    if ($v['id'] === $obs)
                    {

                        $data['fetchData'] = $v;
                        break;
                    }
                }
                $html = $this->load->view('vitals/vital-details', $data, TRUE);
                $this->respond(200, $html);
            }
            else
            {
                $data['noDataMessage'] = "No data available for this host";
                $this->load->view('/vitals/nohost', $data);
            }
        }
        else
        {
            $data['noDataMessage'] = "Cannot generate detailed view, insufficient parameters.";
            $this->load->view('/vitals/nohost', $data);
        }
    }

}
