<?php

namespace App\Components\Forms;


use App\Model\Entities\Security\User as UserEntity;
use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Facades\UserFacade;
use App\Model\Translator;
use App\Model\User;
use Nette\Forms\Form;
use Throwable;
use Tracy\Debugger;

class AttachCredentialsFormFactory 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('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', 'Attach');

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

        return $form;
    }

    /**
     * @param BootstrapForm $form
     * @param $values
     */
    public function formSucceeded(BootstrapForm $form, $values)
    {
        if (!$this->user->isLoggedIn()) {
            $form->addError('You must by logged in.');
            return;
        }

        /** @var UserEntity $user */
        $user = $this->user->getUserEntity();

        try {
            $this->userFacade->getUserAccountWriter()->attachCredentials($user, $values->email, $values->password);
        } catch(Throwable $e) {
            Debugger::log($e);
            $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) {
            // Email is not used - everything is ok
        }
    }
}