import {Terminal} from 'xterm';
import { Readline } from "xterm-readline";
import { FitAddon } from 'xterm-addon-fit';

const term = new Terminal();
const rl = new Readline();
term.options.scrollback = 1000;
const fit = new FitAddon();
term.loadAddon(fit);
term.loadAddon(rl);
term.open(document.getElementById('console'));
fit.fit();

let lineHandler = (l: string) => { console.log("Default handler", l); };

async function readForever() {
  while (true) {
    const l = await rl.read("");
    lineHandler(l);
  }
}
readForever();

const params: {[key:string]: string} =
  location.search.substr(1).split('&')
    .reduce((o, s) => { const [k, v] = s.split('='); o[k] = v; return o;},
            {} as {[key:string]: string});

function connectTerm() {
  lineHandler = () => {};
  term.writeln("\x1b[0mConnecting to server...");
  const wsurl = (window.localStorage['allow_wsurl'] !== "true" || params.wsurl === undefined) ?
    "wss://ws.blastmud.org/wsgame" : params.wsurl;
  let webSocket = new WebSocket(wsurl);
  webSocket.addEventListener('open', (event) => {
    fit.fit();
    lineHandler = (l: string) => { console.log("Send handler", l); webSocket.send(l); }
    term.writeln("\x1b[0mConnected");
  });
  webSocket.addEventListener('close', (event) => {
    lineHandler = connectTerm;
    term.writeln("\x1b[0mDisconnected; use r (followed by enter) to reconnect.");
  });
  webSocket.addEventListener('error', (event) => {
    term.writeln("\x1b[0mNetwork error with connection.");
  });
  webSocket.addEventListener('message', (msg) => {
    fit.fit();
    term.write(msg.data.replaceAll("\r", "")
      .replaceAll("\n", "\r\n"));
  });
}

if ('serviceWorker' in navigator) navigator.serviceWorker.register('service-worker.js');

term.focus();
connectTerm();
