<?php

namespace app\models;

use OS\PB\Message;
use OS\PB\Packet;
use yii\web\BadRequestHttpException;

final class Wrapper extends \yii\base\Model {

    /**
     * Returns a `OS\PB\Message` object which includes the already
     * serialized `OS\PB\Packet` as a `RoutedPacket`.
     * 
     * @param   string  $binary         The serialized packet to be wrapped as a Message.
     * @param   int     $ttl            The Time To Live for the message. Default: 0.
     * @param   int     $correlationId  A correlation ID if relevant. Default: 0.
     * 
     * @return  OS\PB\Message
     * 
     * @access  public
     */

    public function setWrappedMessage(string $binary, int $ttl = 0, int $correlationId = 0): Message {
        return new Message([
            "RoutedPacket" => $binary,
            "TimeStampMs" => round(microtime(true) * 1000),
            "TimeToLive" => $ttl,
            "CorrelationId" => $correlationId,
        ]);
    }


    /**
     * Loads the parsed packet and extract the attached `OS\PB\Message`. Once
     * extracted, it finds the `Routed Packet` packet and return's the binary
     * data.
     * 
     * @param   string  $binary The wrapped `OS\PB\Packet` binary string.
     * 
     * @return  string  Unwrapped packet.
     * 
     * @access  public
     */

    public function unwrapMessage(string $binary): string {
        $packet = new Packet();
        $packet->mergeFromString($binary);

        $messages = $packet->getMessages();
        if (count($messages) == 0) {
            throw new BadRequestHttpException("Passed Protobuf has no message");
        }

        /** @var \OS\PB\Message $firstMessage */
        $firstMessage = $messages[0];
        if ($firstMessage->getRoutedPacket() !== "") {
            return $firstMessage->getRoutedPacket();
        }

        return '';
    }
}
