<?php

use App\Core\Database;
use App\Teamtable\Team;
use App\Teamtable\TeamMapper;
use App\Timetable\Time;
use App\Timetable\TimeMapper;

class Cardreader
{
    public PDO $dbh;

    public TeamMapper $teamMapper;

    public TimeMapper $timeMapper;

    public function __construct(Database $database)
    {
        $this->dbh = $database->conn;
        $this->teamMapper = new TeamMapper($this->dbh);
        $this->timeMapper = new TimeMapper($this->dbh);
    }

    /**
     * Returns: 
     * 0 created team
     * 1 started counting
     * 2 counted too fast! 
     * 3 counted round
     * 4 counted round, new best!
     */
    public function receive(string $cardnumber, int $timeout): int 
    {
        $team = $this->teamMapper->getByCardnumber($cardnumber);
        if (!$team)
        {
            // team does not exist, lets create it
            $team = new Team;
            $team->setCardnumber($cardnumber);
            $this->teamMapper->create($team);
            return 0;
        }

        // team exists, insert into time table
        // and update team best time
        $prev_time = $this->timeMapper->getLatestByTeamId($team->id);
        $new_time = new Time;
        $new_time->setTeamId($team->id);
        $new_time = $this->timeMapper->create($new_time);

        if ($prev_time === NULL)
        {
            // team has not ran previously 
            return 1;
        }

        $diff = $new_time->date->getTimestamp() - $prev_time->date->getTimestamp();
        if ($diff <= $timeout)
        {
            $this->timeMapper->delete($new_time->id); // i mean... it works?
            return 2;
        }

        $team->rounds += 1;
        $this->teamMapper->update($team);

        if ($team->bestTime === NULL)
        {
            $team->bestTime = $diff;
            $this->teamMapper->update($team);
        }
        
        if ($diff < $team->bestTime)
        {
            $team->bestTime = $diff;
            $this->teamMapper->update($team);
            return 4;
        }
        return 3;
    }
}