<?php


namespace Mainto\RpcServer\Protocol\Common;


use Mainto\RpcServer\Util\Binary;
use Mainto\RpcServer\Util\Bytes\Bytes;
use Mainto\RpcServer\Util\IO\Reader;
use Mainto\RpcServer\Util\IO\Writer;
use Mainto\RpcServer\Util\Reader\LittleEndianReader;

class MapReadWrite {
    public static function littleReadMapFrom(array &$map, Reader $reader) {
        $littleEndianReader = new LittleEndianReader($reader);

        $mapLen = $littleEndianReader->readerUint8();

        if ($mapLen > 0) {
            for ($i = 0; $i < $mapLen; $i++) {
                $keySize = $littleEndianReader->readerUint8();

                $key = $littleEndianReader->read($keySize);
                $valueLen = $littleEndianReader->readerUint8();

                $values = [];

                for ($j = 0; $j < $valueLen; $j++) {
                    $valueSize = $littleEndianReader->readerUint16();
                    $values[] = $littleEndianReader->read($valueSize);
                }

                $map[$key] = $values;
            }
        }

        return $littleEndianReader->getTotalReaderSize();
    }

    public static function littleWriteMapTo(array $map, Writer $writer) {
        $buffer = Bytes::newBuffer();

        $buffer->writeByte(Binary::intToUint8(count($map)));

        foreach ($map as $key => $values) {
            $buffer->writeByte(Binary::intToUint8(strlen($key)));
            $buffer->writeString($key);

            $buffer->writeByte(Binary::intToUint8(count($values)));
            foreach ($values as $value) {
                $buffer->writeByte(Binary::$littleEndian::intToUint16(strlen($value)));
                $buffer->writeString($value);
            }
        }

        return $buffer->writeTo($writer);
    }
}