import { PeerManager } from "../src/PeerManager.ts";
import { generateID } from "IDUtils";
import nodeDataChannel from 'npm:node-datachannel';
import nodeDatachannelPolyfill from 'npm:node-datachannel/polyfill';

nodeDataChannel.initLogger('Info');

// import {RTCPeerConnection} from 'npm:node-datachannel/polyfill';

// deno install --allow-scripts=npm:node-datachannel --entrypoint ddln_bootstrap.ts
//   constructor(userID: string, peerID: string, isBootstrapPeer: boolean) {

declare type ID = string;

interface Config {
    userID:ID
    peerID:ID
}

let configJSON;
let config:Config;
let configFilename = 'ddln_bootstrap_config.json';
try {
    configJSON = Deno.readTextFileSync(configFilename);
    config = JSON.parse(configJSON) as Config;
    console.log("Loaded config file: ", config);
} catch (e) {
    console.log("Config file not found, creating...");
    const initialConfig = {
        userID: generateID(),
        peerID: generateID()
    };

    console.log(initialConfig);

    Deno.writeTextFileSync(configFilename, JSON.stringify(initialConfig));

    config = initialConfig;
}

// Polyfill RTCPeerConnection and friends
const global = (globalThis as any);
for (const [functionName, func] of Object.entries(nodeDatachannelPolyfill)) {
    global[functionName] = func;
}

console.log("ddln bootstrap peer starting...");

// console.log(nodeDatachannelPolyfill);

const isBootstrapPeer = true;
const peerManager = new PeerManager(config.userID, config.peerID, isBootstrapPeer);

peerManager.registerRPC('announceUsers', (sendingPeerID: string, userIDs: string[]) => {
    console.log(`Got announceUsers from ${sendingPeerID} ${userIDs}`);
});

peerManager.connect();