<?php

$roomMapping = [
];

$passThroughMapping = [
];

include_once("monoformat_schema.php");
include_once("monoformat_structured.php");

function replaceTalkInfo($str, $talks) {
    return preg_replace_callback("/\\$\\{([^}]*)\\}/", function ($matches) use ($talks) {
        if (str_contains($matches[1], ".")) {
            [$id, $what] = explode(".", $matches[1], 2);
            $id = (int) $id;
            if ($id < 0 || $id >= count($talks)) {
                return "";
            }
            $talk = $talks[$id];
            if (array_key_exists($what, $talk)) {
                return $talk[$what];
            } else {
                return "";
            }
        } else {
            return "";
        }
    }, $str);
}

if (isset($_GET["mac"]) and array_key_exists($_GET["mac"], $passThroughMapping)) {
    $fn = $passThroughMapping[$_GET["mac"]];
    if (is_dir($fn)) {
        $d = opendir($fn);
        $files = [];
        while (($e = readdir($d)) !== false) {
            if (str_ends_with($e, ".bin")) {
                array_push($files, $fn . "/" . $e);
            }
        }
        sort($files);
        if (!count($files)) {
            die("No files found");
        }
        $n = (time() / 60) % count($files);
        $fn = $files[$n];
    }
    Header("Content-Type: application/octet-stream");
    readfile($fn);
    exit(0);
}

if (!isset($_GET["mac"]) or !array_key_exists($_GET["mac"], $roomMapping)) {
    /* We didn't find this device in the mapping, so let's just
     * send a default file to the user.
     */
    Header("Content-Type: application/octet-stream");
    readfile(dirname(__FILE__) . "/noroom.bin");
    exit(0);
}

$roomGUID = strtolower($roomMapping[$_GET["mac"]]);

$pretalx = json_decode(file_get_contents("schedule.json"), true);

$roomName = null;
foreach ($pretalx["schedule"]["conference"]["rooms"] as $room) {
    $thisRoomGUID = strtolower($room["guid"]);
    if ($thisRoomGUID === $roomGUID) {
        $roomName = $room["name"];
        break;
    }
}
if ($roomName === null) {
    die("Room not found!");
}

$talks = [];
$now = new DateTimeImmutable("now");

foreach ($pretalx["schedule"]["conference"]["days"] as $day) {
    if (!array_key_exists($roomName, $day["rooms"])) {
        continue;
    }
    $roomTalks = $day["rooms"][$roomName];
    foreach ($roomTalks as $t) {
        [$h, $m] = explode(":", $t["duration"]);
        $duration = $h * 3600 + $m * 60;
        $duration = DateInterval::createFromDateString("$duration sec");
        $speakers = [];
        foreach ($t["persons"] as $person) {
            array_push($speakers, $person["name"]);
        }
        $talkBegin = new DateTimeImmutable($t["date"]);
        $talkEnd = $talkBegin->add($duration);
        if ($talkEnd < $now) {
            continue;
        }
        $talk = [
            "Time" => $talkBegin->format("H:i"),
            "Duration" => $duration->format("H:i"),
            "Persons" => implode(", ", $speakers),
            "Title" => $t["title"],
            "_start" => $talkBegin,
            "_end" => $talkEnd,
        ];
        array_push($talks, $talk);
    }
}

$template = file_get_contents(dirname(__FILE__) . "/template.bin");
$template = monoformat\parseFile($template);

if (count($template->sections) != 1 or $template->sections[0]->sectionType() != monoformat\SectionType::AlwaysDrawn) {
    die("Invalid section in template file");
}

$elements = [];
for ($i = 0; $i < $template->sections[0]->elementCount(); ++$i) {
    array_push($elements, $template->sections[0]->elementAt($i));
}

$end_template = file_get_contents(dirname(__FILE__) . "/endscreen.bin");
$end_template = monoformat\parseFile($end_template);

if (count($end_template->sections) != 1 or $end_template->sections[0]->sectionType() != monoformat\SectionType::AlwaysDrawn) {
    die("Invalid section in end screen template file");
}

$end_elements = [];
for ($i = 0; $i < $end_template->sections[0]->elementCount(); ++$i) {
    array_push($end_elements, $end_template->sections[0]->elementAt($i));
}

$n = 42;
$last = false;
if ($n > count($talks)) {
    $n = count($talks);
    $last = true;
}

$lastEnd = 0;
$outputFile = new monoformat\File();
if (!$last) {
    $section = new monoformat\ExpiryDateSection();
    $section->setExpiryDate($talks[$n - 1]["_end"]->getTimestamp());
    array_push($outputFile->sections, $section);
}
for ($i = 0; $i < $n; ++$i) {
    $subTalks = array_slice($talks, $i);
    $end = $subTalks[0]["_end"]->getTimestamp();
    $section = new monoformat\TimeBasedDrawnSection();
    $section->setDrawOnFront(true);
    $section->setDrawOnBack(true);
    $section->setClearBeforeDrawing(true);
    $section->setStartTimestamp($lastEnd);
    $section->setEndTimestamp($end);
    foreach ($elements as $element) {
        if ($element->elementType() == monoformat\ElementType::ClippedText) {
            $x = $element->x();
            $y = $element->y();
            $width = $element->width();
            $height = $element->height();
            $textFlags = $element->textFlags();
            $fontIndex = $element->fontIndex();
            $text = replaceTalkInfo($element->text(), $subTalks);
            $element = new monoformat\ClippedTextElement($x, $y, $width, $height, $textFlags, $fontIndex, $text);
        } else if ($element->elementType() == monoformat\ElementType::HScrollText) {
            $x = $element->x();
            $y = $element->y();
            $width = $element->width();
            $height = $element->height();
            $textFlags = $element->textFlags();
            $flags = $element->flags();
            $scrollSpeed = $element->scrollSpeed();
            $fontIndex = $element->fontIndex();
            $text = replaceTalkInfo($element->text(), $subTalks) . "  ";
            $element = new monoformat\HScrollTextElement($x, $y, $width, $height, $textFlags, $flags, $scrollSpeed, $fontIndex, $text);
        }
        $section->appendElement($element);
    }
    array_push($outputFile->sections, $section);
    $lastEnd = $end;
}
if ($last) {
    $section = new monoformat\TimeBasedDrawnSection();
    $section->setDrawOnFront(true);
    $section->setDrawOnBack(true);
    $section->setClearBeforeDrawing(true);
    $section->setStartTimestamp($lastEnd);
    // Set this far enough in the future that it doesn't matter
    $section->setEndTimestamp($lastEnd + 86400 * 300);
    foreach ($end_elements as $element) {
        $section->appendElement($element);
    }
    array_push($outputFile->sections, $section);
}

Header("Content-Type: application/octet-stream");
print(monoformat\serializeFile($outputFile));

?>
