<?php

namespace App\Model;

use Nette;
use Nette\Security\Passwords;


/**
 * First management.
 */
class GameManager extends Nette\Object
{

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


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

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

    public function GenerateStart($key)
    {
        RETURN $this->database->query('INSERT INTO p_guilty', array('KEY' => $key, 'JUDGE' => rand(0,1), 'STAGE' => 1));
    }

    public function GetGuilty($key)
    {
        return $this->database->query('SELECT JUDGE FROM p_guilty WHERE `KEY`=?', $key)->fetchfield('JUDGE');
    }

    public function GetStage($key)
    {
        return $this->database->query('SELECT STAGE FROM p_guilty WHERE `KEY`=?', $key)->fetchField('STAGE');
    }

    public function InsertResult($key, $result)
    {
        RETURN $this->database->query('UPDATE p_guilty SET `RESULT` = ? WHERE `KEY`=?', $result, $key);
    }

    public function NextStage($key, $stage)
    {
        RETURN $this->database->query('UPDATE p_guilty SET `STAGE` = ? WHERE `KEY`=?', $stage, $key);
    }

    public function GetResult($key)
    {
        return $this->database->query('SELECT RESULT FROM p_guilty WHERE `KEY`=?', $key)->fetchField("RESULT");
    }

    public function getStartTime($key)
    {
        return $this->database->query('SELECT START_TIME FROM p_timer WHERE `KEY`=?', $key)->fetch();
    }

    public function getStopTime($key)
    {
        return $this->database->query('SELECT START_TIME FROM p_timer WHERE `KEY`=? AND STAGE=1', $key)->fetch();
    }

    public function getNumberOfGames ()
    {
        return $this->database->query('SELECT COUNT(*) FROM p_guilty WHERE STAGE=2')->fetchfield();
    }

    public function getNumberOfWinGames ()
    {
        return $this->database->query('SELECT COUNT(*) FROM p_guilty WHERE STAGE=2 AND (RESULT=1 or RESULT=4)')->fetchfield();
    }
    public function setEndTime($params)
    {
        return $this->database->query('INSERT INTO p_timer', $params);

    }

}



