<?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\MainBundle\Security\PasswordRecover;

use Chill\MainBundle\Entity\User;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class PasswordRecoverVoter extends Voter
{
    final public const ASK_TOKEN = 'CHILL_PASSWORD_ASK_TOKEN';

    final public const TRY_TOKEN = 'CHILL_PASSWORD_TRY_TOKEN';

    /**
     * @var PasswordRecoverLocker
     */
    protected $locker;

    /**
     * @var RequestStack
     */
    protected $requestStack;

    protected $supported = [
        self::TRY_TOKEN,
        self::ASK_TOKEN,
    ];

    public function __construct(PasswordRecoverLocker $locker, RequestStack $requestStack)
    {
        $this->locker = $locker;
        $this->requestStack = $requestStack;
    }

    protected function supports($attribute, $subject): bool
    {
        if (!\in_array($attribute, $this->supported, true)) {
            return false;
        }

        return true;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        switch ($attribute) {
            case self::TRY_TOKEN:
                if (true === $this->locker->isLocked('invalid_token_global')) {
                    return false;
                }

                $ip = $this->requestStack->getCurrentRequest()->getClientIp();

                if (true === $this->locker->isLocked('invalid_token_by_ip', $ip)) {
                    return false;
                }

                return true;

            case self::ASK_TOKEN:
                if (true === $this->locker->isLocked('ask_token_invalid_form_global')) {
                    return false;
                }

                $ip = $this->requestStack->getCurrentRequest()->getClientIp();

                if (true === $this->locker->isLocked('ask_token_invalid_form_by_ip', $ip)) {
                    return false;
                }

                if ($subject instanceof User) {
                    if (true === $this->locker->isLocked('ask_token_success_by_user', $subject)) {
                        return false;
                    }
                }

                return true;
        }

        return false;
    }
}
