<?php /** @noinspection PhpIllegalPsrClassPathInspection */

namespace Kicken\Chat;


abstract class StreamSocketClient extends StreamSocket {
    private string $mReadBuffer = '';
    private string $mWriteBuffer = '';
    const READ_PACKET_SIZE = 4096;

    public function hasPendingWrites() : bool{
        return strlen($this->mWriteBuffer) > 0;
    }

    public function nowReadable() : void{
        if ($this->mResource === null){
            return;
        }

        $data = fread($this->mResource, self::READ_PACKET_SIZE);
        if ($data === ''){
            $this->close();
        } else {
            $this->mReadBuffer .= $data;
        }
    }

    public function nowWritable() : void{
        if ($this->mResource === null || $this->mWriteBuffer === ''){
            return;
        }

        $len = fwrite($this->mResource, $this->mWriteBuffer);
        $this->mWriteBuffer = substr($this->mWriteBuffer, $len);
    }

    public function writeSocket(string $data) : void{
        $this->mWriteBuffer .= $data;
        $this->nowWritable();
    }

    public function readAll() : string{
        $s = $this->mReadBuffer;
        $this->mReadBuffer = '';

        return $s;
    }
}