<?php

declare(strict_types=1);

namespace App\Forms;

use Nette\Application\UI\Form;
use Nette\Security\AuthenticationException;
use Nette\Security\User;
use Nette\SmartObject;
use Nette\Utils\ArrayHash;


class SignInFormFactory {

	use SmartObject;

	private $formFactory;

	private $user;

	public function __construct(FormFactory $factory, User $user) {

		$this->formFactory = $factory;
		$this->user = $user;

	}

	public function create(callable $onSuccess) {
		$form = $this->formFactory->create();
		$form->addText('username', 'Jméno')->setRequired()
			->setHtmlAttribute('class', 'login_name')->setHtmlAttribute('class','form-control form'); 
		$form->addPassword('password', 'Heslo')
			->setHtmlAttribute('class', 'login_pass')->setHtmlAttribute('class','form-control form'); 
		$form->addSubmit('login', 'Přihlásit')
			->setHtmlAttribute('class', 'login_button')->setHtmlAttribute('class','btn btn-secondary form-btn'); 


		$form->onSuccess[] = function (Form $form, ArrayHash $values) use ($onSuccess) {
			try {
				$this->user->login($values->username, $values->password);
				$onSuccess($form, $values); 
			} catch (AuthenticationException $e) {
				$form->addError('Zadané přihlašovací jméno nebo heslo nejsou správně.');
			}
		};

		return $form;
	}
}
