<?php
declare(strict_types=1);

namespace App\Filter\DoctrineFilter;

use App\Attribute\ActivityYearConstraintAware;
use App\Service\Constraint\ActivityYearConstraint;
use App\Service\Utils\StringsUtils;
use Doctrine\ORM\Mapping\ClassMetadata;
use Exception;

/**
 * Classe DateTimeFilter qui définie la requête SQL devant être ajoutée aux Entités possédant l'annotation DateTimeConstraintAware
 */
final class ActivityYearFilter extends AbstractTimeFilter
{
    private ActivityYearConstraint $activityYearConstraint;

    /**
     * Méthode surchargée de SQLFilter
     * @param ClassMetadata $targetEntity
     * @param string $targetTableAlias
     * @return string
     * @throws Exception
     */
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias): string
    {
        if(!$this->hasParameter('_time_constraint')
            || !(bool) StringsUtils::unquote($this->getParameter('_time_constraint'))
            || !$this->hasParameter('accessId')
        ) {
            return '';
        }

        $yearConstraintAware = $targetEntity->getReflectionClass()->getAttributes(ActivityYearConstraintAware::class)[0] ?? null;
        $startFieldName = $yearConstraintAware?->getArguments()['startYearFieldName'] ?? null;
        $endFieldName = $yearConstraintAware?->getArguments()['endYearFieldName'] ?? null;
        if ($startFieldName === '' || is_null($startFieldName) || $endFieldName === '' || is_null($endFieldName)) {
            return '';
        }

        $accessId = intval(StringsUtils::unquote($this->getParameter('accessId')));

        $constraints = $this->activityYearConstraint->invoke($accessId);

        $fields = [
            ActivityYearConstraint::START_KEY => $startFieldName,
            ActivityYearConstraint::END_KEY => $endFieldName
        ];

        return $this->constructQuery($constraints, $targetTableAlias, $fields);
    }

    /**
     * Permets d'assurer l'injection de dépendance du service YearTimeConstraint
     * @param ActivityYearConstraint $activityYearConstraint
     *
     */
    public function setActivityYearConstraint(ActivityYearConstraint $activityYearConstraint): void{
        $this->activityYearConstraint = $activityYearConstraint;
    }
}