import * as plugins from './plugins.js';

export class ConnectorPublic {
  private tunnel: plugins.tls.TLSSocket | null = null;

  constructor() {
    this.createTunnel();
    this.listenOnPorts();
  }

  private createTunnel(): void {
    const options = {
      key: plugins.fs.readFileSync('path/to/key.pem'),
      cert: plugins.fs.readFileSync('path/to/cert.pem'),
    };

    const server = plugins.tls.createServer(options, (socket: plugins.tls.TLSSocket) => {
      this.tunnel = socket;
      console.log('Tunnel established with LocalConnector');
    });

    server.listen(4000, () => {
      console.log('PublicRemoteConnector listening for tunnel on port 4000');
    });
  }

  private listenOnPorts(): void {
    // Example for port 80, adapt for port 443 similarly
    // Note: TLS for the initial connection might not apply directly for HTTP/HTTPS traffic without additional setup
    const options = {
      key: plugins.fs.readFileSync('path/to/key.pem'),
      cert: plugins.fs.readFileSync('path/to/cert.pem'),
    };

    plugins.tls.createServer(options, (socket: plugins.tls.TLSSocket) => {
      console.log('Received connection, tunneling to LocalConnector');
      if (this.tunnel) {
        socket.pipe(this.tunnel).pipe(socket);
      } else {
        console.log('Tunnel to LocalConnector not established');
        socket.end();
      }
    }).listen(80); // Repeat this block for any other ports you wish to listen on
  }
}
