<?php


namespace Webapp\Core\Voter;

use Shared\Authentication\Voter\SiteRoleVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Webapp\Core\Entity\ValueList;
use Webapp\Core\Enumeration\VariableTypeEnum;

class ValueListVoter extends Voter
{
    public const POST_VALUE_LIST = 'POST_VALUE_LIST';

    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    protected function supports($attribute, $subject): bool
    {
        $supportsAttribute = in_array($attribute, [self::POST_VALUE_LIST]);
        $supportsSubject = $subject instanceof ValueList;
        return $supportsAttribute && $supportsSubject;
    }

    /**
     * @param string $attribute
     * @param ValueList $subject
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if (!$token->isAuthenticated()) {
            return false;
        }
        switch ($attribute) {
            case self::POST_VALUE_LIST:
                return $this->security->isGranted(SiteRoleVoter::ROLE_PLATFORM_MANAGER, $subject->getSite()) && (
                        $subject->getVariable() === null || (
                            $subject->getVariable()->getType() === VariableTypeEnum::ALPHANUMERIC &&
                            ($subject->getVariable()->getValueList() === null || $subject->getVariable()->getValueList()->getId() === $subject->getId())
                        ));
        }

        return false;
    }
}
