<?php


/**
 * Class BaseHealthDiagnosticSqlBuilder
 */
abstract class BaseHealthDiagnosticSqlBuilder implements HealthDiagnosticSqlBuilderInterface
{
    protected $userName;
    /**
     * @var array
     */
    protected $data;

    /**
     * BaseHealthDiagnosticSqlBuilder constructor.
     */
    final public function __construct($userName)
    {
        $this->userName = $userName;

        if (!property_exists($this, 'nonOverlappedSql')) {
            throw new LogicException(get_class($this) . ' must have a $nonOverlappedSql variable');
        }
    }

    /**
     * @return string
     */
    abstract public function getSql(): string;

    /**
     * @return string
     */
    abstract public function getReportSql(): string;


    /**
     * Extend sql by adding where not in (needed health diagnostic report).
     * It means: Select hosts from category A and these hosts shouldn't be in category B
     * It needs to avoid hosts overlapping into different categories.
     *
     * @param HealthDiagnosticSqlBuilderInterface $category
     *
     * @return $this
     */
    public function doNotOverlapWithCategory(HealthDiagnosticSqlBuilderInterface $category): HealthDiagnosticSqlBuilderInterface
    {
        $operator = strstr($this->getNonOverlappedSql(), 'WHERE') ? 'AND' : 'WHERE';
        $this->nonOverlappedSql = sprintf($this->getNonOverlappedSql() . " $operator HostKey NOT IN (%s)", $category->getSql());

        return $this;
    }

    /**
     * @return string
     */
    public function getNonOverlappedSql(): string
    {
        return empty($this->nonOverlappedSql) ? $this->getSql() : $this->nonOverlappedSql;
    }

    /**
     * @param array $data
     *
     * @return  HealthDiagnosticSqlBuilderInterface
     */
    public function setParams(array $data): HealthDiagnosticSqlBuilderInterface
    {
        $this->data = $data;
        return $this;
    }

}
