<?php

/**
 * Class AgentNotRunRecentlySqlBuilder
 */
class AgentNotRunRecentlySqlBuilder extends BaseHealthDiagnosticSqlBuilder
{
    //agentexecutioninterval::int * 1.3 - needs to avoid report blinking, because agentexecutioninterval is approximate time
    /**
     * @var string
     */
    protected $sql = 'SELECT result.hostkey FROM (
                        SELECT agentstatus.HostKey 
                        FROM agentstatus 
                        LEFT JOIN hosts ON hosts.hostkey = agentstatus.hostkey
                        WHERE extract(epoch from (lastReportTimeStamp::timestamp - lastagentlocalexecutiontimestamp::timestamp)) > GREATEST(600, agentexecutioninterval::int  * 1.3)
                      ) AS result 
                      WHERE hostkey NOT IN (SELECT hostkey FROM health_diagnostics_dismissed WHERE username = \'%s\' AND report_type = \'%s\' )';

    /**
     * @var string
     */
    protected $nonOverlappedSql;

    /**
     * @var string
     */
    protected $reportSql = 'SELECT h.Hostkey as key,h.hostname as "Host name", lastreporttimestamp as "Last report collected", agentstatus.lastagentlocalexecutiontimestamp as "Last agent local execution time"  
                            FROM hosts h 
                            LEFT JOIN agentstatus  ON agentstatus.Hostkey = h.Hostkey';


    /**
     * @return string
     */
    public function getSql(): string
    {
        $sql = sprintf($this->sql, $this->userName, BaseHealthDiagnostic::NOT_RUN_RECENTLY_TYPE);
        return $sql;
    }

    /**
     * Extend report sql by adding where in (report sql).
     * It needs to include in report only needed hosts.
     *
     * @return string
     */
    public function getReportSql(): string
    {
        $this->reportSql = sprintf($this->reportSql . ' WHERE h.HostKey IN (%s)', $this->getNonOverlappedSql());
        return $this->reportSql;
    }
}
