<?php

declare(strict_types=1);

namespace App\Forms;

use App\Model\DuplicateNameException;
use App\Model\UserManager;
use Nette\Application\UI\Form;
use Nette\SmartObject;
use Nette\Utils\ArrayHash;

class SignUpFormFactory {

	use SmartObject;

	private $formFactory;

	private $userManager;

	public function __construct(FormFactory $factory, UserManager $userManager) {
		$this->formFactory = $factory;
		$this->userManager = $userManager;
	}

	public function create(callable $onSuccess) {

		$form = $this->formFactory->create();
		#$form;
		$form->addText('username', 'Jméno')->setRequired()->setHtmlAttribute('class','form-control form');
		$form->addPassword('password', 'Heslo')->setHtmlAttribute('class','form-control form');
		$form->addPassword('password_repeat', 'Heslo znovu')->setOmitted()->setRequired(false)
			->addRule(Form::EQUAL, 'Hesla nejsou stejná.', $form['password'])->setHtmlAttribute('class','form-control form');
		$form->addSubmit('register', 'Registrovat')->setHtmlAttribute('class','btn btn-secondary form-btn');

		$form->onSuccess[] = function (Form $form, ArrayHash $values) use ($onSuccess) {
			try {

				$this->userManager->register($values->username, $values->password);
				$onSuccess($form, $values); 
			} catch (DuplicateNameException $e) {
				$form['username']->addError($e->getMessage());
			}
		};

		return $form;
	}
}
