<?php

require_once APPPATH . '/libraries/Cf_REST_Controller.php';

class HostComplianceList extends Cf_REST_Controller
{


    function __construct()
    {
        parent::__construct();
        $this->username = $this->session->userdata('username');
        $this->load->model(array('host_model'));
        $this->load->helper('elements_creator');
    }

    function tablemetadata_get($colour)
    {

        $tableColsName = array();


        switch ($colour)
        {
            case "red":
            $tableColsName = array(
                    array('sTitle' => "<input type='checkbox' id='check-all' name='check-all'>", "sClass" => "select-col", "sWidth" => "15px", "mRender" => 'checkbox_formatter', 'aTargets' => array(0)),
                    array('sTitle' => "Host", 'aTargets' => array(1)),
                    array('sTitle' => "IP", 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => array(2)),
                    array('sTitle' => " ", 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => array(3))
                );
            break;
            case "green":
                $tableColsName = array(
                    array('sTitle' => "<input type='checkbox' id='check-all' name='check-all'>", "sClass" => "select-col", "sWidth" => "15px", "mRender" => 'checkbox_formatter', 'aTargets' => array(0)),
                    array('sTitle' => "Host", 'aTargets' => array(1)),
                );
                break;
            case "bb":
                $tableColsName = array(
                    array('sTitle' => " <input type='checkbox' id='check-all' name='check-all'>", "sClass" => "select-col", "sWidth" => "15px", "mRender" => 'checkbox_formatter', 'aTargets' => array(0)),
                    array('sTitle' => "Host", 'aTargets' => array(1)),
                    array('sTitle' => "Time", 'bSortable' => false, 'mRender' => 'timestamp_formatter', 'aTargets' => array(2)),
                    array('sTitle' => "Problem", 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => array(3))
                );
                break;

        }


        $output = array("aoColumnDefs" => $tableColsName);


        $this->respond_ok(json_encode($output));
    }

    function tabledata_post()
    {

        $result = array();
        $getparams = $this->uri->uri_to_assoc(4);
        $rows = intval($this->param('iDisplayLength'));
        $echo = intval($this->param('sEcho'));


        $displayStarts = intval($this->param('iDisplayStart'));



        $page_number = intval(ceil($displayStarts / $rows), 10) + 1;
        $includes = $this->param_includes();
        $excludes = $this->param_excludes();
        $colour = $this->param('colour', true);

        $datarows = array();


        switch ($colour)
        {
            case "red":
                $result = $this->host_model->getHostByColorFromPromiseStatus('red', $this->username, $includes, $excludes, $rows, $page_number);
                foreach ($result['rows'] as $index => $r)
                {
                    $r[1] = create_host_link_element($r[0], $r[1]);
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = $this->_makePromiseNotKeptLink($hostKey, 'notkept');
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }
                break;
            case "green":
                $result = $this->host_model->getHostByColorFromPromiseStatus('green', $this->username, $includes, $excludes, $rows, $page_number);
                foreach ($result['rows'] as $index => $r)
                {
                    $r[1] = create_host_link_element($r[0], $r[1]);
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }
                break;
            case "bb":
                $blue =  $this->host_model->getHostByColorFromPromiseStatus('blue', $this->username, $includes, $excludes, $rows, $page_number);
                $black =  $this->host_model->getHostByColorFromPromiseStatus('black', $this->username, $includes, $excludes, $rows, $page_number);
                $result = array();
                $result['rows'] = array_merge($blue['rows'],$black['rows']);
                $result['rowCount'] = $blue['rowCount'] + $black['rowCount'];
                foreach ($blue['rows'] as $index => $r)
                {
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = "Connection error";
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }

                foreach ($black['rows'] as $index => $r)
                {
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = "Agent not executed";
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }

        }

        $jsonObj = new stdClass();
        $jsonObj->page = $page_number;

        $totalPageNumber = ceil($result['rowCount'] / $rows);
        $jsonObj->iTotalRecords = $totalPageNumber;
        $jsonObj->iTotalDisplayRecords = $result['rowCount'];
        $jsonObj->sEcho = $echo;

        $paginationData = paging($page_number, $rows, $result['rowCount'], 5);
        $jsonObj->userdata = $paginationData;


        $jsonObj->aaData = $datarows;

        $this->respond_ok(json_encode($jsonObj));
    }

    function _makePromiseNotKeptLink($data, $type)
    {

        $logType = $type;
        $title = array(
            'notkept' => 'List promises not kept',
            'repaired' => 'List promises repaired'
        );
        $url = site_url('advancedreports/external');
        $escapedData = $this->db->escape_str($data);
        $query  = sprintf('SELECT DISTINCT h.hostname AS "Host name",
                                 p.bundlename AS "Bundle name",
                                 p.promisehandle AS "Promise handle",
                                 p.promiser AS "Promiser",
                                 p.promiseoutcome AS "Promise outcome",
                                 p.changetimestamp AS "Change time",
                                 p.logmessages AS "Log messages"
                                FROM promiseexecutions p INNER JOIN hosts h ON h.hostkey = p.hostkey
                                WHERE p.HOSTKEY=\'%s\' AND p.promiseoutcome=\'NOTKEPT\' ORDER BY p.changetimestamp DESC',$escapedData);
        $encoded = rawurlencode(base64_encode($query));

        $class = convertSHAToPK_SHA($data);
        $includes = rawurlencode(base64_encode($class));


        $link = $url .'/sql/'. $encoded . "/includes/".$includes.'/title/Promise not kept report';
        return anchor($link, $title[$logType], 'onclick="event.stopPropagation();"');
    }


}

