<?php

namespace Comitium5\DesignerBundle\Factory\Search\Filter;

use Elastica\Query\BoolQuery;
use Elastica\Query\Range;

/**
 * Class DateShouldFilter
 *
 * @author David Carrascosa <david@bab-soft.com>
 * @package Comitium5\DesignerBundle\Factory\Search\Filter
 */
class DateShouldFilter
{
    const LESS_THAN = 'lt';
    const LESS_THAN_EQUAL = 'lte';
    const GREATER_THAN_EQUAL = 'gte';
    const GREATER_THAN = 'gt';

    /**
     * @var string
     */
    private $field;

    /**
     * @var \DateTime
     */
    private $date;

    /**
     * @var string
     */
    private $expression;

    /**
     * DateShouldFilter constructor.
     *
     * @param string $field
     * @param \DateTime $date
     * @param string $expression
     */
    public function __construct(string $field, \DateTime $date, string $expression = self::GREATER_THAN_EQUAL)
    {
        $this->field = $field;
        $this->date = $date;
        $this->expression = $expression;
    }

    /**
     * @param BoolQuery $boolQuery
     */
    public function __invoke(BoolQuery $boolQuery): void
    {
        $match = new Range();

        $match->addField($this->field, [$this->expression => $this->date->format('Y-m-d\\TH:i:s')]);

        $this->addFilter($boolQuery, $match);
    }

    /**
     * @param BoolQuery $boolQuery
     * @param Range $match
     */
    protected function addFilter(BoolQuery $boolQuery, Range $match): void
    {
        $boolQuery->addShould($match);
    }
}
