<?php
declare(strict_types=1);

namespace FreshCloud\Mail\NetSocket;

final class InMemorySocket implements SocketInterface
{
    private string $buffer = '';
    private bool $connected = false;

    public function connect(SocketConfig $config): void
    {
        $this->connected = true;
    }

    public function read(int $length): string
    {
        if (!$this->connected) {
            throw new \RuntimeException('Socket is not connected');
        }
        $data = substr($this->buffer, 0, $length);
        $this->buffer = substr($this->buffer, $length);
        return $data;
    }

    public function write(string $data): void
    {
        if (!$this->connected) {
            throw new \RuntimeException('Socket is not connected');
        }
        $this->buffer .= $data;
    }

    public function close(): void
    {
        $this->connected = false;
        $this->buffer = '';
    }

    public function isConnected(): bool
    {
        return $this->connected;
    }
}