<?php


namespace Mainto\RpcServer\Util\Net\Conn;


use FFI;
use Mainto\RpcServer\Util\Bytes\Buffer;
use Mainto\RpcServer\Util\Bytes\Bytes;
use Mainto\RpcServer\Util\Net\Address;
use Mainto\RpcServer\Util\Net\Conn;

class FastMQConn implements Conn {

    /**
     * @var mixed
     */
    private $mq;
    private string $address;

    private Buffer $buf;

    private string $fixedBuf;

    public function __construct (string $address, $mq) {
        $this->mq = $mq;
        $this->address = $address;
        $this->buf = Bytes::newBuffer();
        $this->fixedBuf = Bytes::makeBytes(4096);
    }

    public static function newConnByAddress($address) {
        $mq = require __DIR__.'/../../../Util/FastMQ/ffi.php';
        $res = $mq->openMQ($address);
        if (FFI::string($res) != "ok") {
            throw new \RuntimeException($res);
        }
        $instance = new self($address, $mq);

        $instance->write("connect");

        return $instance;
    }

    public function close () {
    }

    public function localAddr (): Address {
    }

    public function remoteAddr (): Address {
    }

    public function read (int $size): ?string {
        if ($this->buf->empty()) {
            $this->buf->reset();

            $len = $this->mq->readPackage($this->address, $this->fixedBuf);
            $this->buf->write(substr($this->fixedBuf, 0, $len));
        }

        return $this->buf->read($size);
    }

    public function write (string $p): int {
        $this->mq->write($this->address, $p, strlen($p));

        return strlen($p);
    }
}