<?php

namespace App\Components\Forms;


use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Facades\UserFacade;
use App\Model\Translator;
use App\Model\User;
use Nette\Forms\Form;

class RegisterFormFactory extends BaseFormFactory
{
    /**
     * @var UserFacade
     */
    protected $userFacade;
    /**
     * @var User
     */
    protected $user;

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

        $this->userFacade = $userFacade;
        $this->user = $user;
    }


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

        $form->addText('nickname', 'Nickname:')
            ->setRequired('Please enter your nickname.');

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

        $form->addPassword('password', 'Password:')
            ->addRule(Form::MIN_LENGTH, 'Password must have at least %d characters.', 6);

        $form->addPassword('passwordCheck', 'Password confirm:')->setOmitted(true)
            ->addRule(Form::EQUAL, 'Your passwords does not match.', $form['password']);

        $form->addSubmit('submit', 'Sign up');

        $form->onValidate[] = array($this, 'formValidate');

        return $form;
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        try {
            $userEntity = $this->userFacade->getUserAccountWriter()->registerUserWithCredentials($values->nickname, $values->email, $values->password);
            $this->user->setExpiration('20 minutes', TRUE);
            $this->user->login($userEntity);
        } catch( \Exception $e) {
            // todo: find possible exceptions
            $form->addError('Registration has failed.');
        }
    }

    public function formValidate(BootstrapForm $form, $values)
    {
        try {
            $this->userFacade->getUserAccountReader()->findCredentialsByEmail($values->email);
            $form['email']->addError('E-mail is already used.');
        } catch (RecordNotFoundException $e) {
            // is ok, do nothing
        }
    }
}