<?php

namespace Modules\Printer\Drivers;

use Exception;
use Modules\Printer\Contracts\DriverInterface;

class TcpPrinterDriver implements DriverInterface
{
    /**
     * Create a new instance of TcpPrinterDriver
     *
     * @param string $host
     * @param int $port
     * @param int $timeout
     */
    public function __construct(protected string $host, protected int $port = 9100, protected int $timeout = 5)
    {
    }

    /** @inheritDoc */
    public function send(string $buffer): void
    {
        $sock = fsockopen($this->host, $this->port, $errno, $errorMessage, $this->timeout);
        if (!$sock) throw new Exception(__("printer::messages.failed_connect_tcp", ["message" => $errorMessage]));
        fwrite($sock, $buffer);
        fclose($sock);
    }
}
