<?php


namespace Shared\Authentication\Voter;

use Shared\Authentication\Entity\RelUserSite;
use Shared\Authentication\Entity\Site;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;

class SiteVoter extends Voter
{
    public const SITE_EDIT = 'SITE_EDIT';
    public const SITE_GET = 'SITE_GET';
    public const SITE_POST = 'SITE_POST';
    public const SITE_DELETE = 'SITE_DELETE';

    private $security;

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

    protected function supports($attribute, $subject): bool
    {
        $supportsAttribute = in_array($attribute, [self::SITE_EDIT, self::SITE_GET, self::SITE_POST, self::SITE_DELETE]);
        $supportsSubject = $subject instanceof Site;
        return $supportsAttribute && $supportsSubject;
    }

    /**
     * @param string $attribute
     * @param Site $subject
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if (!$token->isAuthenticated()) {
            return false;
        }
        switch ($attribute) {
            case self::SITE_DELETE:
            case self::SITE_EDIT:
                if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_SITE_ADMIN', $subject)) {
                    return true;
                }
                break;
            case self::SITE_GET:
                if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_EXPERIMENTER', $subject)) {
                    return true;
                }
                break;
            case self::SITE_POST:
                if ($this->security->isGranted('ROLE_ADMIN') ||
                    ($this->security->isGranted('ROLE_SITE_ADMIN') &&
                        count(array_filter($subject->getUserRoles()->toArray(), function (RelUserSite $rel){
                            return $rel->getRole() === RelUserSite::SITE_ADMIN && $this->security->getUser() === $rel->getUser();
                        }) )) > 0
                ) {
                    return true;
                }
                break;
        }

        return false;
    }
}