<?php

namespace Ignite\Core\Events;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Mail;
use Ignite\Core\Emails\Enrolled;
use Ignite\Core\Entities\Group;
use Ignite\Core\Entities\User as UserModel;

class User
{
    /**
     * @var Mailer
     */
    private $mailer;

    /**
     * User constructor.
     *
     * @param Mailer $mailer
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle user login events.
     *
     * @param  Login $event
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function onUserLogin($event)
    {
        /** @var \Ignite\Core\Auth\Impersonation $impersonation */
        $impersonation = app('impersonation');
        if ($impersonation->isImpersonating()) {
            $impersonation->stopImpersonating();
        }
        $event->user->update(['last_login_at' => now()]);
    }

    /**
     * When a user enrolls event.
     *
     * @param Registered $event
     */
    public function onUserEnrolled($event)
    {
        // TODO: Make this configurable.
        $group = Group::where('key', 'participant')->first(); // Or: 5

        /** @var UserModel $user */
        $user = $event->user;
        $user->status = UserModel::STAT_PENDING;
        $user->groups()->attach($group->getKey());
        $user->save();

        $this->mailer->later(now()->addSeconds(30), new Enrolled($user));
    }

    /**
     * When a user sets a password.
     *
     * @param PasswordReset $event
     */
    public function onUserSetPassword($event)
    {
        /** @var UserModel $user */
        $user = $event->user;

        if ($user->status === UserModel::STAT_PENDING) {
            $user->status = UserModel::STAT_ACTIVE;
            event(new EnrollmentComplete($user));
        }

        $user->save();
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param  \Illuminate\Events\Dispatcher $events
     */
    public function subscribe($events)
    {
        $events->listen(
            Login::class,
            'Ignite\Core\Events\User@onUserLogin'
        );

        $events->listen(
            Registered::class,
            'Ignite\Core\Events\User@onUserEnrolled'
        );

        $events->listen(
            PasswordReset::class,
            'Ignite\Core\Events\User@onUserSetPassword'
        );
    }
}
