<?php $app = require '../../app/inc.php';

use App\Teamtable\TeamMapper;
use App\Timetable\TimeMapper;
use App\SSE\EventLoop;
use App\SSE\StopEventLoopException;

$teamMapper = new TimeMapper($app->database->conn);
$timeMapper = new TimeMapper($app->database->conn);

/**
 * Send events to client with Server-Sent Events(SSE)
 */
$sse = new EventLoop();
$sse->interval = 1; 

$persist_obj = new class {
        public ?int $prev_last_insert = NULL;
    };

$sse->start(
    function () use ($timeMapper, $teamMapper, &$persist_obj) {

        $time = $timeMapper->getLatest();

        if ($time)
        {
            $last_insert = $time->date->getTimestamp();

            if ( $persist_obj->prev_last_insert == NULL
                || $last_insert > $persist_obj->prev_last_insert
            ) {
                $persist_obj->prev_last_insert = $last_insert;

                return($timeMapper->getAll());
            }
        }
    }
);