<?php


namespace Webapp\Core\Voter;

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\Factor;
use Webapp\Core\Entity\Protocol;

class ProtocolVoter extends Voter
{
    public const PROTOCOL_POST = 'PROTOCOL_POST';

    private $security;

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

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

    /**
     * @param string $attribute
     * @param Protocol $subject
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if (!$token->isAuthenticated()) {
            return false;
        }
        $site = $subject->getSite();
        switch ($attribute) {
            case self::PROTOCOL_POST:
                if ($this->security->isGranted('ROLE_PLATFORM_MANAGER', $site) &&
                    $subject->getFactors()->count() <= 3 &&
                    !$subject->getFactors()->exists(function ($index, Factor $factor) {
                        return $factor->getOrder() === null;
                    })
                ) {
                    return true;
                }
                break;
        }

        return false;
    }
}
