<?php

/**
 * $SQLData['rowCount'] - total in db
 * $SQLData['rows'] - actual rows
 */
class sqlhooks_hooks
{
    public $url;
    public $url_by_name;
    public $totalRows;

    public function __construct()
    {
        $this->url         = site_url('/hosts');
        $this->url_by_name = site_url('/assets/host_assets_by_name');
    }

    public function linkContent($CI, $SQLData)
    {
        $this->totalRows = count($SQLData['rows']);

        if (!empty($CI->session->userdata('username'))) {
            $CI->load->model(['health_diagnostic_model', 'advancedreports_model']);
            $CI->health_diagnostic_model->setUserName($CI->session->userdata('username'));
            $failedHosts = $CI->health_diagnostic_model->getHealthFailures($CI->advancedreports_model);
        } else {
            $failedHosts = [];
        }

        // loop on all headers and try to determin if hostkey field already exists in result
        $hostKeyPos = $this->_getHostkeyFieldPos($SQLData['header']);

        // save all host keys, because next loop will change hostkey to link
        $hostsKeys = $this->_saveHostkeys($hostKeyPos, $SQLData['rows']);

        foreach ($SQLData['header'] as $item => $field)
        {
            $columnName = strtolower(str_replace(' ', '', $field['columnName']));
            $columnType = strtolower(str_replace(' ', '', $field['columnType']));

            switch ($columnName)
            {

                case 'hostkey':

                    $this->_updateDataWithHostLinkFromHostKey($SQLData['rows'], $hostsKeys, $item);
                    if (sizeof($failedHosts) > 0) {
                        $this->addHealthIssueDirective($SQLData['rows'], $hostsKeys, $item, $failedHosts);
                    }
                    break;

                case 'changedetails':

                    $this->updateDiffData($SQLData['rows'], $item);
                    break;

                case 'hostname':

                    if ($hostKeyPos !== -1)
                    {
                        // we have hostkey in result, so use it
                        $this->_updateDataWithHostLinkFromHostKey($SQLData['rows'], $hostsKeys, $item);
                    }
                    else
                    {
                        // if no - use name and link assets page by name
                        $this->_updateDataWithHostLinkFromHostName($SQLData['rows'], $item);
                    }

                    break;

                default:
                    if (strtolower($columnType) == 'array')
                    {
                        for ($i = 0; $i < $this->totalRows; $i++)
                        {
                            $SQLData['rows'][$i][$item] = implode(' <br /> ', $SQLData['rows'][$i][$item]);
                        }
                    }
                    break;
            }
        }

        return $SQLData;
    }


     /**
     * Scan header array for hostkey field and return pos or -1 if not found
     *
     * @param <array> $headerArray - sql result header
     * @return <int>
     */
    function _getHostkeyFieldPos($headerArray)
    {
        $hostKeyPos = -1;

        foreach ($headerArray as $item => $field)
        {
            $columnName = strtolower(str_replace(' ', '', $field['columnName']));
            if ($columnName === 'hostkey')
            {
                $hostKeyPos = $item;
                break;
            }
        }

        return $hostKeyPos;
    }


    /**
     * Modify field and return hostlink created from hostkey. Result - field converted to link
     *
     * @param <reference to array> $data - data array
     * @param <array> $hostsKeys - array of hostkeys
     * @param <int> $fieldPos - position of field which we convert to url
     */
    private function _updateDataWithHostLinkFromHostKey(&$data, $hostsKeys, $fieldPos)
    {
        for ($i = 0; $i < $this->totalRows; $i++)
        {
            $data[$i][$fieldPos] = $this->_buildHostUrlByKey($hostsKeys[$i], $data[$i][$fieldPos]);
        }
    }

    private function addHealthIssueDirective(&$data, $hostsKeys, $fieldPos, $failedHosts = [])
    {
        for ($i = 0; $i < $this->totalRows; $i++)
        {
            $hostsKey = $hostsKeys[$i];
            if (isset($failedHosts[$hostsKey])) {
                $data[$i][$fieldPos] .= '<span health-issue category="'. $failedHosts[$hostsKey] .'" ></span>';
            }
        }
    }

    /**
     * Modify field and return diff presented as HTML code
     *
     * @param <reference to array> $data - data array
     * @param <int> $fieldPos - position of field which we convert to url
     */
    private function updateDiffData(&$data, $fieldPos)
    {
        for ($i = 0; $i < $this->totalRows; $i++) {
            $diffData = $data[$i][$fieldPos];
            $preview = strlen($diffData[0]) > 40 ? substr($diffData[0], 0, 40) . '...' : $diffData[0];
            // detect diff by +/- presence at the start of the change details
            $data[$i][$fieldPos] = preg_match("/^[\+|\-]/", $data[$i][$fieldPos][0])
                ? '<div>' . $preview .'
                       <button diff-to-html class="btn btn-mini btn-diff" >
                           <i class="icon-eye-open"></i> show diff
                       </button>
                       <textarea class="hide">'. json_encode($diffData) .'</textarea>
                   </div>'
                : $data[$i][$fieldPos];
        }
    }


    /**
     * Modify field and return hostlink Trying to find hostkey by given hostname. Result - field converted to link
     *
     *
     * @param <object> $CI - CodeIgniter object
     * @param <array reference> $data - SQL result
     * @param <int> $fieldPos - position of field to modify
     */
    private function _updateDataWithHostLinkFromHostName(&$data, $fieldPos)
    {
        for ($i = 0; $i < $this->totalRows; $i++)
        {
            $data[$i][$fieldPos] = $this->_buildHostUrlByName($data[$i][$fieldPos], $data[$i][$fieldPos]);
        }
    }


    /**
     * Return html link like  <a href="/hosts/SHA=HOST_KEY">FIELD</a>
     *
     * @param <string> $hostkey
     * @param <string> $fieldValue
     * @return <string>
     */

    private function _buildHostUrlByKey($hostKey, $fieldValue)
    {
        return sprintf('<a href="%s/%s">%s</a>', $this->url, $hostKey, $fieldValue);
    }


    /**
     * Return html link like  <a href="/assets/host_assets_by_name/node001">FIELD</a>
     *
     * @param <string> $hostkey
     * @param <string> $fieldValue
     * @return <string>
     */

    private function _buildHostUrlByName($hostName, $fieldValue)
    {
        return sprintf('<a href="%s/%s">%s</a>', $this->url_by_name, urlencode($hostName), $fieldValue);
    }


    /**
     * Save hostkeys into separated array
     *
     * @param <int> $hostKeyPos  - position of hostkey field in array
     * @param <array> $data - result from SQL
     * @return <array>
     */
    private function _saveHostkeys($hostKeyPos, $data)
    {
        $hostsKeys = array();

        if ($hostKeyPos !== -1)
        {
            for ($i = 0; $i < $this->totalRows; $i++)
            {
                $hostsKeys[$i] = $data[$i][$hostKeyPos];
            }
        }

        return $hostsKeys;
    }
}

?>