<?php

namespace App\Forms;

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


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

	private $userM;

    private $GameM;


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

        $this->GameM = $g;

    }


	/**
	 * @return Form
	 */
	public function create()
	{
		$form = new Form;
		$form->addText('username', 'Key:')
			->setRequired('Please enter your username.')->setAttribute("autocomplete","off");

		$form->addSubmit('send', 'Sign in');

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


	public function formSucceeded(Form $form, $values)
	{
		$this->user->setExpiration('4 hours', TRUE);

		
		try {
			$this->user->login($values->username);
            $playerID = $this->GameM->GetStartofGame($this->user->id);
            if ($playerID == 2) {
                $this->GameM->GenerateStart($this->user->id);
            }
		} catch (Nette\Security\AuthenticationException $e) {
			$form->addError($e->getMessage());
		}
		
		try {
			$this->userM->startTimer($this->user->id);
		} catch(\Exception $e) {} 
		 
	}

}
