<?php

namespace App\Model;

use Nette;
use Nette\Security\Passwords;
use Nette\Utils\DateTime;


/**
 * Users management.
 */
class UserManager extends Nette\Object implements Nette\Security\IAuthenticator
{
	const
		TABLE_NAME = 'd_access_keys',
		COLUMN_ID = 'ID',
		COLUMN_NAME = 'key_hash';


	/** @var Nette\Database\Context */
	private $database;


	public function __construct(Nette\Database\Context $database)
	{
		$this->database = $database;
	}

	public function startTimer($user)
	{
        $data = array( 'KEY' => $user, 'START_TIME' => new DateTime(), 'STAGE' => 0);

        $this->database->table('d_timer')->insert($data);

	}

	/**
	 * Performs an authentication.
	 * @return Nette\Security\Identity
	 * @throws Nette\Security\AuthenticationException
	 */
	public function authenticate(array $credentials)
	{
		list($username) = $credentials;

		$row = $this->database->table(self::TABLE_NAME)->where(self::COLUMN_NAME, $username)->fetch();

		if (!$row) {
			throw new Nette\Security\AuthenticationException('The key is incorrect.', self::IDENTITY_NOT_FOUND);
		}

		$arr = $row->toArray();
		return new Nette\Security\Identity($row[self::COLUMN_ID], 'user', $arr);
	}

    public function GenerateKey($username)
    {
        RETURN $this->database->query('INSERT INTO d_access_keys', array('key_hash' => $username));
    }

    public function CheckKey($key)
    {
        return $this->database->query('SELECT CASE WHEN EXISTS (SELECT 1 FROM d_access_keys where`key_hash`=?) THEN 1 ELSE 2 END', $key)->fetchField();
    }

    /**
	 * Adds new user.
	 * @param  string
	 * @param  string
	 * @return void
	 */
	public function add($username, $password)
	{
		try {
			$this->database->table(self::TABLE_NAME)->insert(array(
				self::COLUMN_NAME => $username,
				self::COLUMN_PASSWORD_HASH => Passwords::hash($password),
			));
		} catch (Nette\Database\UniqueConstraintViolationException $e) {
			throw new DuplicateNameException;
		}
	}

}



class DuplicateNameException extends \Exception
{}
