<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Doctrine\DQL;

use Doctrine\ORM\Query\AST\Functions\DateDiffFunction;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * Extract postgresql function
 * https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT.
 *
 * Usage : EXTRACT(field FROM timestamp)
 * TODO allow interval usage -> EXTRACT(field FROM interval)
 */
class Extract extends FunctionNode
{
    private string $field;

    private \Doctrine\ORM\Query\AST\Node|string|null $value = null;
    // private PathExpression $value;
    // private FunctionNode $value;
    // private DateDiffFunction $value;

    public function getSql(SqlWalker $sqlWalker)
    {
        return sprintf(
            'EXTRACT(%s FROM %s)',
            $this->field,
            $this->value->dispatch($sqlWalker)
        );
    }

    public function parse(Parser $parser)
    {
        $parser->match(\Doctrine\ORM\Query\TokenType::T_IDENTIFIER);
        $parser->match(\Doctrine\ORM\Query\TokenType::T_OPEN_PARENTHESIS);

        $parser->match(\Doctrine\ORM\Query\TokenType::T_IDENTIFIER);
        $this->field = $parser->getLexer()->token['value'];

        $parser->match(\Doctrine\ORM\Query\TokenType::T_FROM);

        // $this->value = $parser->ScalarExpression();
        $this->value = $parser->ArithmeticPrimary();

        $parser->match(\Doctrine\ORM\Query\TokenType::T_CLOSE_PARENTHESIS);
    }
}
