<?php


namespace App\Components\Forms;


use App\Model\Entities\Security\User as UserEntity;
use App\Model\Facades\TranslatorFacade;
use App\Model\Translator;
use App\Model\User;

class TranslateGuiFormFactory extends BaseFormFactory
{
    /** @var TranslatorFacade */
    protected $translatorFacade;

    /** @var User */
    protected $user;

    public function __construct(Translator $translator, TranslatorFacade $translatorFacade, User $user)
    {
        parent::__construct($translator);

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


    public function create() : BootstrapForm
    {
        $form = parent::create();
        $form->addHidden('id');
        $form->addText('translation');
        $form->addSubmit('submit', 'Save');

        return $form;
    }


    public function formSucceeded(BootstrapForm $form, $values)
    {
        if (!$this->user->isLoggedIn()) {
            $form['translation']->addError('You must be logged in.');
        }

        /** @var UserEntity $user */
        $user = $this->user->getUserEntity();
        $translation = $this->translatorFacade->getTranslationReader()->findGuiTranslationById($values->id);
        $this->translatorFacade->getTranslationWriter()->translate($translation, $values->translation, $user);
    }
}