<?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 Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PasswordRecoverEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var PasswordRecoverLocker
     */
    protected $locker;

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

    public static function getSubscribedEvents(): array
    {
        return [
            PasswordRecoverEvent::INVALID_TOKEN => [
                ['onInvalidToken'],
            ],
            PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM => [
                ['onAskTokenInvalidForm'],
            ],
            PasswordRecoverEvent::ASK_TOKEN_SUCCESS => [
                ['onAskTokenSuccess'],
            ],
        ];
    }

    public function onAskTokenInvalidForm(PasswordRecoverEvent $event)
    {
        // set global lock
        $this->locker->createLock('ask_token_invalid_form_global', null);

        // set ip lock
        if ($event->hasIp()) {
            $this->locker->createLock('ask_token_invalid_form_by_ip', $event->getIp());
        }
    }

    public function onAskTokenSuccess(PasswordRecoverEvent $event)
    {
        $this->locker->createLock('ask_token_success_by_user', $event->getUser());
    }

    public function onInvalidToken(PasswordRecoverEvent $event)
    {
        // set global lock
        $this->locker->createLock('invalid_token_global', null);

        // set ip lock
        if ($event->hasIp()) {
            $this->locker->createLock('invalid_token_by_ip', $event->getIp());
        }
    }
}
