<?php

/*
 * This file is part of the Claroline Connect package.
 *
 * (c) Claroline Consortium <consortium@claroline.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Claroline\OpenBadgeBundle\Security\Voter;

use Claroline\CoreBundle\Entity\User;
use Claroline\CoreBundle\Security\Voter\AbstractVoter;
use Claroline\OpenBadgeBundle\Entity\Evidence;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

class EvidenceVoter extends AbstractVoter
{
    public function getClass()
    {
        return Evidence::class;
    }

    /**
     * @param Evidence $object
     */
    public function checkPermission(TokenInterface $token, $object, array $attributes, array $options)
    {
        $currentUser = null;
        if ($token->getUser() instanceof User) {
            $currentUser = $token->getUser();
        }

        $badge = $object->getAssertion()->getBadge();
        $recipient = $object->getRecipient();

        switch ($attributes[0]) {
            case self::OPEN:
                // has grant rights on the badge or is owner
                if ($this->isGranted('GRANT', $badge)
                    || (!empty($currentUser) && !empty($recipient) && $currentUser->getId() === $recipient->getId())) {
                    return VoterInterface::ACCESS_GRANTED;
                }

                return VoterInterface::ACCESS_DENIED;

            case self::CREATE:
            case self::EDIT:
            case self::ADMINISTRATE:
            case self::DELETE:
                // has grant rights on the badge
                if ($this->isGranted('GRANT', $badge)) {
                    return VoterInterface::ACCESS_GRANTED;
                }

                return VoterInterface::ACCESS_DENIED;
        }

        return VoterInterface::ACCESS_ABSTAIN;
    }

    public function getSupportedActions()
    {
        return [self::OPEN, self::CREATE, self::EDIT, self::DELETE];
    }
}
