<?php
require_once 'AlertSQL.php';

class FileChangedAlert extends AlertSQL
{
    /**
     * @var HttpClientInterface
     */
    private $restClient;

    /**
     * FileChangedAlert constructor.
     */
    function __construct()
    {
        parent::__construct();
    }

    /**
     * @param HttpClientInterface $client
     */
    public function setRestClient(HttpClientInterface $client)
    {
        $this->restClient = $client;
    }

    /**
     * @param $alert
     * @param $rule
     * @param $includes
     * @param $excludes
     *
     * @return int
     */
    function getStatus($alert, $rule, $includes, $excludes)
    {
        $data = [
            'query' => $this->getSql($rule),
            'hostContextInclude' => $includes,
            'hostContextExclude' => $excludes
        ];

        $response = $this->restClient->post('/query', $data);
        $response = json_decode($response, JSON_OBJECT_AS_ARRAY);

        $failHosts = sizeof(reset($response["data"])['rows']);
        $totalHosts = $this->ci->host_model->getHostCountByContext($alert->username, $includes);

        $alertStatus['status'] = $failHosts > 0 ? 'fail' : 'success';
        $alertStatus['failHosts'] = $failHosts;
        $alertStatus['totalHosts'] = $totalHosts;

        return $alertStatus;
    }

    /**
     * @param $alert
     * @param $rule
     *
     * @return int
     */
    public function getCountFailHosts($alert, $rule)
    {
        $includes = $this->utils_getIncludesFromAlert($alert);
        $excludes = $this->utils_getExcludesFromAlert($alert);

        $data = [
            'query' => $this->getSql($rule),
            'hostContextInclude' => $includes,
            'hostContextExclude' => $excludes
        ];

        $response = $this->restClient->post('/query', $data);
        $response = json_decode($response, JSON_OBJECT_AS_ARRAY);

        $failHosts = reset($response["data"])['rows'];

        return sizeof($failHosts);
    }

    /**
     * @param $alert
     * @param $rule
     * @param $limit
     *
     * @return array
     */
    public function getHostListWithHeader($alert, $rule, $limit)
    {

        $includes = $this->utils_getIncludesFromAlert($alert);
        $excludes = $this->utils_getExcludesFromAlert($alert);

        $data = [
            'query' => $this->getWidgetReportSQL($rule),
            'hostContextInclude' => $includes,
            'hostContextExclude' => $excludes,
            'limit' => $limit
        ];

        $response = $this->restClient->post('/query', $data);
        $response = json_decode($response, JSON_OBJECT_AS_ARRAY);
        $result = array();
        $result['header'] = $response["data"][0]['header'];
        $result['rows'] = $response["data"][0]['rows'];

        return $result;
    }


    /**
     * @param $rule
     *
     * @return string
     */
    private function getWidgetReportSQL($rule)
    {
        $query = 'SELECT hosts.HostName AS "Host name",  FileChangesLog.hostkey,
                  FileChangesLog.filename AS "File name", FileChangesLog.changetimestamp AS "Change timestamp"
                  FROM FileChangesLog LEFT JOIN hosts  ON hosts.hostkey = FileChangesLog.hostkey
                  ' . $this->getSqlFilter($rule);
        return $query;
    }

    /**
     * @param $rule
     *
     * @return string
     */
    private function getSql($rule)
    {
        return 'SELECT hostkey FROM FileChangesLog ' . $this->getSqlFilter($rule);
    }

    /**
     * @param $rule
     *
     * @return string
     */
    private function getSqlFilter($rule)
    {
        $fileName = $rule->fileChangedConditions['fileName'];
        if ($rule->fileChangedConditions['condition'] == 'matches') {
            $fileName = '%' . $fileName . '%';
        }

        $escapedFileName = $this->ci->db->escape_str($fileName);

        $hours = isset($rule->fileChangedConditions['timePeriod']) && !empty($rule->fileChangedConditions['timePeriod'])
            ? (int)$rule->fileChangedConditions['timePeriod']
            : 24;

        return " WHERE  FileName LIKE '$escapedFileName' AND changetimestamp >= (NOW() - INTERVAL '$hours HOURS') ";
    }

    /**
     * @param $rule
     *
     * @return string
     */
    public function getStatSqlString($rule)
    {
        return $this->getSql($rule);
    }

}
