<?php


namespace Mainto\RpcServer\Util\Reader;


use Mainto\RpcServer\Util\Binary;
use Mainto\RpcServer\Util\IO\Reader;

class LittleEndianReader implements Reader {
    /**
     * @var Reader
     */
    private Reader $reader;

    private int $totalReaderSize = 0;

    public function __construct (Reader $reader) {
        $this->reader = $reader;
    }

    public function readerUint8 (): int {
        $b = $this->readFull(1);

        return ord($b[0]);
    }

    public function readerUint16 (): int {
        $b = $this->readFull(2);

        return Binary::$littleEndian::strToUint16($b);
    }

    public function readerUint32 (): int {
        $b = $this->readFull(4);

        return Binary::$littleEndian::strToUint32($b);
    }

    public function readerUint64 (): int {
        $b = $this->readFull(8);

        return Binary::$littleEndian::strToUint64($b);
    }

    private function readFull (int $size): string {
        $read = "";

        $allReader = 0;
        while (true) {
            $read .= $this->reader->read($size);

            $allReader += strlen($read);
            $this->totalReaderSize += strlen($read);

            if ($allReader >= $size) {
                return $read;
            }
        }

        return "";
    }

    public function read (int $size): string {
        return $this->reader->read($size);
    }

    /**
     * @return int
     */
    public function getTotalReaderSize (): int {
        return $this->totalReaderSize;
    }
}