<?php

/**
 * Class HealthDiagnosticReportModel
 */
class HealthDiagnosticReportModel extends BaseHealthDiagnostic
{
    /**
     * @var int
     */
    private $timeCheckForBlueHost;
    /**
     * @var int
     */
    private $hostsCollisionsThreshold;
    /**
     * @var array
     *
     * Order of array elements is important.
     * Every element will not contain hosts from previous ones.
     */
    public static $reportTypes = [
        self::HOSTS_NEVER_COLLECTED_TYPE,
        self::DELETED_HOSTS_REPORT_TYPE,
        self::NOT_RECENTLY_COLLECTED_TYPE,
        self::SAME_IDENTITY_TYPE,
        self::NOT_RUN_RECENTLY_TYPE,
        self::LAST_AGENT_RUN_UNSUCCESSFUL_TYPE
    ];

    /**
     * @var $sqlBuilder HealthDiagnosticSqlBuilderInterface
     */
    private $sqlBuilder;

    /**
     * HealthDiagnosticReportModel constructor.
     *
     * @param $userName
     * @param $reportType
     */
    public function __construct(string $userName, string $reportType)
    {
        parent::__construct($userName);
        $settings = json_decode(cfapi_settings_get($this->userName), JSON_OBJECT_AS_ARRAY);
        $this->timeCheckForBlueHost = time() - ($settings['data'][0]['blueHostHorizon']);
        $this->hostsCollisionsThreshold = $settings['data'][0]['hostsCollisionsThreshold'] ?: 3;
        $this->setSqlBuilder($reportType);
    }


    /**
     * @param $reportType
     *
     * @throws Exception
     */
    private function setSqlBuilder($reportType)
    {
        $reportTypes = self::$reportTypes;
        // remove host not reported type from report types because we need to avoid overlapping rest of
        // reports with this one
        unset($reportTypes[array_search(self::HOSTS_NEVER_COLLECTED_TYPE, $reportTypes)]);
        $reportTypes = array_values($reportTypes);

        $params = [
            'timeCheckForBlueHost' => $this->timeCheckForBlueHost,
            'hostsCollisionsThreshold' => $this->hostsCollisionsThreshold
        ];
        $builder = HealthDiagnosticSqlBuilderFactory::createSqlBuilder($reportType, $this->userName)->setParams($params);
        $index = array_search($reportType, $reportTypes);
        // get previous types to exclude
        $overlappedTypes = array_slice($reportTypes, 0, $index);
        foreach ($overlappedTypes as $overlappedType) {
            $builder->doNotOverlapWithCategory(
                HealthDiagnosticSqlBuilderFactory::createSqlBuilder($overlappedType, $this->userName)
                ->setParams($params)
            );
        }

        $this->sqlBuilder = $builder;
    }

    /**
     * @return mixed|string
     */
    public function getSql()
    {
        return $this->sqlBuilder->getReportSql();
    }
}
