'use strict';

const net = require('net');
const adapter = require('@node-escpos/adapter');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }

const net__default = /*#__PURE__*/_interopDefaultLegacy(net);

class Network extends adapter.Adapter {
  constructor(address, port = 9100, timeout = 3e4) {
    super();
    this.address = address;
    this.port = port;
    this.timeout = timeout;
    this.device = new net__default.Socket();
  }
  open(callback) {
    const connection_timeout = setTimeout(() => {
      this.device.destroy();
      callback && callback(
        new Error(`printer connection timeout after ${this.timeout}ms`),
        this.device
      );
    }, this.timeout);
    this.device.on("error", (err) => {
      callback && callback(err, this.device);
    }).on("data", (buf) => {
      console.log("printer say:", buf);
    }).connect(this.port, this.address, (err) => {
      clearInterval(connection_timeout);
      this.emit("connect", this.device);
      callback && callback(err ?? null, this.device);
    });
    return this;
  }
  write(data, callback) {
    const handler = (error) => {
      if (callback)
        callback(error ?? null);
    };
    if (typeof data === "string")
      this.device.write(data, handler);
    else
      this.device.write(data, handler);
    return this;
  }
  read(callback) {
    this.device.on("data", (buf) => {
      if (callback)
        callback(buf);
    });
    return this;
  }
  close(callback) {
    this.device.destroy();
    this.emit("disconnect", this.device);
    callback && callback(null, this.device);
    return this;
  }
}

module.exports = Network;
