<?php

namespace App\Forms;

use Nette;
use Nette\Application\UI\Form;
use Nette\Security\User;
use App\Model\UserManager;


class GeneratorFormFactory extends Nette\Object
{
    /** @var User */
    private $user;
    private $userM;

    public function __construct(User $user, \App\Model\UserManager $userM)
    {
        $this->user = $user;
        $this->userM = $userM;
    }


    /**
     * @return Form
     */
    public function create()
    {
        $form = new Form;
        $form->addText('masterkey', 'Masterkey: ');

        $form->addHidden('username')->setValue(md5(rand()));
        $form->addSubmit('sendG', 'Generate New Key');

        $form->addText('key', 'New key: ');
        $form->addSubmit('sendK', 'Insert New key');

        $form->onSuccess[] =
            array($this, 'formSucceeded');
        return $form;
    }


    public function formSucceeded(Form $form, $values)
    {
        $submit = $form->isSubmitted()->getName();
        if ($values['masterkey'] == "agonkrg1665") {
            if ($submit == 'sendG') {
                $check = $this->userM->CheckKey($values['username']);
                if ($check == 2) {
                    $form->addText('text', 'Generated key: ')->setDisabled()->setValue($values['username']);
                    $this->userM->GenerateKey($values['username']);
                }
            }

            if ($submit == 'sendK') {
                $check = $this->userM->CheckKey($values['key']);
                if ($check == 2) {
                    $this->userM->GenerateKey($values['key']);
                    $form->addText('text')->setDisabled()->setValue("The key was created!");
                } else {
                    $form->addText('text')->setDisabled()->setValue("This key already exists!");
                }

            }
        }
        else {
            $form->addText('text')->setDisabled()->setValue("Insert the masterkey first!");
        }

    }

}
