<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ThirdPartyBundle\Security\Voter;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

/**
 * Voter for Third Party.
 */
class ThirdPartyVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
    final public const CREATE = 'CHILL_3PARTY_3PARTY_CREATE';

    final public const SHOW = 'CHILL_3PARTY_3PARTY_SHOW';

    final public const UPDATE = 'CHILL_3PARTY_3PARTY_UPDATE';

    /**
     * @var AuthorizationHelper
     */
    protected $authorizationHelper;

    public function __construct(AuthorizationHelper $authorizationHelper)
    {
        $this->authorizationHelper = $authorizationHelper;
    }

    public function getRoles(): array
    {
        return [
            self::CREATE, self::UPDATE, self::SHOW,
        ];
    }

    public function getRolesWithHierarchy(): array
    {
        return [
            'Third party' => $this->getRoles(),
        ];
    }

    public function getRolesWithoutScope(): array
    {
        return $this->getRoles();
    }

    protected function supports($attribute, $subject)
    {
        if ($subject instanceof ThirdParty) {
            return \in_array($attribute, $this->getRoles(), true);
        }

        if (null === $subject) {
            return self::CREATE === $attribute || self::SHOW === $attribute;
        }

        return false;
    }

    /**
     * @param string          $attribute
     * @param ThirdParty|null $subject
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        return true;
        $user = $token->getUser();

        if (!$user instanceof User) {
            return false;
        }

        return true;
        $centers = $this->authorizationHelper
            ->getReachableCenters($user, $attribute);

        if (null === $subject) {
            return \count($centers) > 0;
        }

        if ($subject instanceof ThirdParty) {
            return \count(\array_intersect($centers, $subject->getCenters()->toArray())) > 0;
        }

        return false;
    }
}
