<?php

declare(strict_types=1);

namespace App\Framework\Http\Emitter;

use App\Framework\Http\Response;
use App\Framework\Http\Responses\AdaptiveStreamResponse;
use InvalidArgumentException;

final class AdaptiveStreamEmitter implements Emitter
{
    public function emit(Response $response): void
    {
        if (! $response instanceof AdaptiveStreamResponse) {
            throw new InvalidArgumentException('Response must be AdaptiveStreamResponse');
        }

        // HTTP Status senden
        http_response_code($response->status->value);

        // Header senden
        foreach ($response->headers->all() as $name => $values) {
            foreach ($values as $value) {
                header("{$name}: {$value}");
            }
        }

        // Playlist/Manifest ausgeben
        echo $response->body;

        if (ob_get_level() > 0) {
            ob_flush();
        }
        flush();
    }
}
