<?php

namespace App\Components\Forms;

use App\Model\Translator;
use Nette;
use Nette\Forms\Form;
use Nette\Security\AuthenticationException;
use Nette\Security\IAuthenticator;
use Nette\Security\User;

class SignFormFactory extends BaseFormFactory
{
	/** @var User */
	protected $user;

	/**
	 * SignFormFactory constructor.
	 * @param Translator $translator
	 * @param User $user
	 */
	public function __construct(Translator $translator, User $user)
	{
		parent::__construct($translator);

		$this->user = $user;
	}


	/**
	 * @return BootstrapForm
	 */
	public function create() : BootstrapForm
	{
		$form = parent::create();

		$form->addText('email', 'E-mail:')
			->addRule(Form::EMAIL, 'Please enter your email.');

		$form->addPassword('password', 'Password:')
			->setRequired('Please enter your password.');

		$form->addCheckbox('remember', 'Keep me signed in');

		$form->addSubmit('send', 'Sign in');

		return $form;
	}


	/**
	 * @param BootstrapForm $form
	 * @param $values
     */
	public function formSucceeded(BootstrapForm $form, $values)
	{
		if ($values->remember) {
			$this->user->setExpiration('14 days', FALSE);
		} else {
			$this->user->setExpiration('20 minutes', TRUE);
		}

		try {
			$this->user->login($values->email, $values->password);
		} catch (AuthenticationException $e) {
			switch ($e->getCode()) {
				case IAuthenticator::IDENTITY_NOT_FOUND:
					$form['email']->addError($e->getMessage());
					break;
				case IAuthenticator::INVALID_CREDENTIAL:
					$form['password']->addError($e->getMessage());
					break;
				default:
					$form->addError($e->getMessage());
					break;
			}
			return;
		}
	}

}
