<?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\JobBundle\Security\Authorization;

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;

/**
 * Class ExportsJobVoter.
 *
 * @author Mathieu Jaumotte mathieu.jaumotte@champs-libres.coop
 */
class ExportsJobVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface, VoterInterface
{
    public const EXPORT = 'CHILL_JOB_EXPORTS';

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

    /**
     * CVVoter constructor.
     */
    public function __construct(AuthorizationHelper $authorizationHelper)
    {
        $this->authorizationHelper = $authorizationHelper;
    }

    /**
     * @return bool
     */
    protected function supports($attribute, $subject)
    {
        if ($subject instanceof Center) {
            return self::EXPORT === $attribute;
        }
        if (null === $subject) {
            return self::EXPORT === $attribute;
        }

        return false;
    }

    /**
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();

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

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

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

        return $this->authorizationHelper->userHasAccess($user, $subject, $attribute);
    }

    /**
     * Return an array of roles, where keys are the hierarchy, and values
     * an array of roles.
     *
     * Example:
     *
     * ```
     * [ 'Title' => [ 'CHILL_FOO_SEE', 'CHILL_FOO_UPDATE' ] ]
     * ```
     */
    public function getRolesWithHierarchy(): array
    {
        return ['JobBundle' => $this->getRoles()];
    }

    /**
     * return an array of role provided by the object.
     *
     * @return string[] array of roles (as string)
     */
    public function getRoles(): array
    {
        return $this->getAttributes();
    }

    /**
     * return roles which doesn't need.
     *
     * @return string[] array of roles without scopes
     */
    public function getRolesWithoutScope(): array
    {
        return $this->getAttributes();
    }

    /**
     * @return array
     */
    private function getAttributes()
    {
        return [self::EXPORT];
    }
}
