<?php

class health_diagnostic_model extends Cf_Model
{
    private $userName = false;
    private $cacheTTL;
    private $statusCacheKey;
    private $failuresCacheKey;

    public function __construct()
    {
        $this->load->driver('cache', ['adapter' => 'file']);
        $this->cacheTTL = $this->config->item('default_cache_ttl');
        parent::__construct();
    }

    public function setUserName($userName)
    {
        $this->userName = $userName;

        $this->statusCacheKey = "{$userName}_HealthStatus";
        $this->failuresCacheKey = "{$userName}_HealthFailures";
    }

    public function getReportData($type)
    {
        $this->load->config('healthDiagnostic');
        $reportData = $this->config->item('healthDiagnosticReports')[$type];

        $result = json_decode(
            $this->getRestClient()->post('/health-diagnostic/report/' . $type, ['limit' => 50]),
            JSON_OBJECT_AS_ARRAY,
        );

        return [
            'sql' => $result['data'][0]['query'],
            'title' => $reportData['title'],
            'description' => $reportData['description'],
            'recommendations' => $reportData['recommendations'],
            'hideDefaultButtons' => array_key_exists('hideDefaultButtons', $reportData)
                ? $reportData['hideDefaultButtons']
                : false,
            'showAdditionalDeleteActions' => array_key_exists('showAdditionalDeleteActions', $reportData)
                ? $reportData['showAdditionalDeleteActions']
                : false,
        ];
    }

    public function getHealthStatus()
    {
        if ($this->statusCacheKey && $this->cache->get($this->statusCacheKey)) {
            return $this->cache->get($this->statusCacheKey);
        }
        $result = json_decode($this->getRestClient()->get('/health-diagnostic/status'), JSON_OBJECT_AS_ARRAY);
        $this->cache->save($this->statusCacheKey, $result, $this->cacheTTL);
        return $result;
    }

    public function getHealthFailures($advancedReportsModel)
    {
        if ($this->failuresCacheKey && $this->cache->get($this->failuresCacheKey)) {
            return $this->cache->get($this->failuresCacheKey);
        }
        $data = $advancedReportsModel->runQuery(
            $this->userName,
            'SELECT hostkey, category FROM health_diagnostics_failures',
        );
        $failedHosts = [];
        if (isset($data['rows']) && is_array($data)) {
            foreach ($data['rows'] as $row) {
                $failedHosts[$row[0]] = $row[1];
            }
        }

        $this->cache->save($this->failuresCacheKey, $failedHosts, $this->cacheTTL);
        return $failedHosts;
    }

    public function dismissHosts($hosts, $type)
    {
        $this->getRestClient()->post('/health-diagnostic/dismiss/' . $type, ['hosts' => $hosts]);
    }

    public function removeFromDismissed($hosts, $type)
    {
        $this->getRestClient()->delete('/health-diagnostic/dismiss/' . $type, ['hosts' => $hosts]);
    }

    public function getDismissedHosts($type)
    {
        return json_decode($this->getRestClient()->get('/health-diagnostic/dismiss/' . $type), JSON_OBJECT_AS_ARRAY);
    }

    public function deleteCache()
    {
        $this->cache->delete($this->statusCacheKey);
        $this->cache->delete($this->failuresCacheKey);
    }
}
