<?php

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

class BatonReader 
{
    public PDO $dbh;

    public TeamMapper $team_mapper;
    public TimeMapper $time_mapper;

    public function __construct(Database $database)
    {
        $this->dbh = $database->conn;
        $this->team_mapper = new TeamMapper($this->dbh);
        $this->time_mapper = 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->team_mapper->getByCardnumber($cardnumber);
        if (!$team)
        {
            // team does not exist, lets create it
            $team = new Team;
            $team->setCardnumber($cardnumber);
            $this->team_mapper->create($team);
            return 0;
        }

        // team exists, insert into time table
        // and update team best time
        $prev_time = $this->time_mapper->getLatestByTeamId($team->id);
        $new_time = new Time;
        $new_time->setTeamId($team->id);
        $new_time = $this->time_mapper->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->time_mapper->delete($new_time->id); // i mean... it works?
            return 2;
        }

        $team->setRounds($team->rounds + 1);
        $this->team_mapper->update($team);

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