import { Server } from 'bittorrent-tracker';
import assert from "assert";
import logging  from '../lib/logging.js';

const log = logging.create("/services/tracker.js");

export const description = "Runs the webtorrent tracker.";

export const options = [
  ["--port <int>", "Port to listen on.", 9001],
  ["--host <ip_addr>", "IP address to listen on.", "0.0.0.0"],
];

export const main = (opts) => {
  const server = new Server({
    udp: false, // enable udp server? [default=true]
    http: true, // enable http server? [default=true]
    ws: true, // enable websocket server? [default=true]
    stats: true, // enable web-based statistics? [default=true]
    filter: (infoHash, params, cb) => {
      log.debug(infoHash, "----------------------------------------------");
      cb(null)
    }
  })

  server.on('error', (err) => {
    // fatal server error!
    log.debug(err.message)
  })

  server.on('warning', (err) => {
    // client sent bad data. probably not a problem, just a buggy client.
    log.debug(err.message)
  })

  server.on('listening', () => {
    // fired when all requested servers are listening
    log.debug('listening on port:', server.http.address().port)
  })

  // start tracker server listening! Use 0 to listen on a random free port.
  server.listen(opts.port, opts.host, (what) => {
    log.debug(`Listening.... ${opts.host}:${opts.port} ${what}`);
  })

  // listen for individual tracker messages from peers:

  server.on('start', (addr) => {
    log.debug('got start message from', addr)
  })

  server.on('complete', (addr) => {
    log.debug('complete', addr);
  });

  server.on('update', (addr) => {
    log.debug('update', addr);
  });

  server.on('stop', (addr) => {
    log.debug('stop', addr);
  });

  const onHttpReq = server.onHttpRequest.bind(server);
  assert(onHttpReq !== undefined, "Bad call to bind.");
}


// see: https://github.com/nodejs/node/issues/35212
process.on('SIGINT', () => process.exit());
