<?php

/**
 * Class HostsUsingSameNameSqlBuilder
 */
class HostsUsingSameNameSqlBuilder extends BaseHealthDiagnosticSqlBuilder
{
    /**
     * @var string
     * hosts.hostname is not always the hostname, it is what you choose as host identifier in Mission Portal.
     */
    protected $sql = '
                      SELECT hostkey FROM hosts 
                      WHERE hostname IN (SELECT hostname FROM hosts GROUP BY hostname HAVING COUNT(*) > 1)
                      AND hostkey NOT IN (
                      SELECT hostkey 
                      FROM health_diagnostics_dismissed 
                      WHERE username = \'%s\' AND report_type = \'%s\' 
                      )';

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

    /**
     * @var string
     * hosts.hostname is not always the hostname, it is what you choose as host identifier in Mission Portal.
     */
    protected $reportSql = 'SELECT h.Hostkey as key,
                                   h.Hostkey as hostkey, 
                                   h.hostname as hostname, 
                                   ipaddress as "IP address", 
                                   lastreporttimestamp as "Last report collected", 
                                   firstreporttimestamp as "First report collected"
                            FROM hosts h ';


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

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

        return $this->reportSql;
    }

}
