

declare const Guacamole: any;

export function openConsole(
  container: HTMLElement,
  wsUrl: string,
  connectData = ""
): { disconnect: () => void; setScale: (scale: number) => void; resize: (width: number, height: number) => void } {
  
  
  const tunnel = new Guacamole.WebSocketTunnel(wsUrl);
  const client = new Guacamole.Client(tunnel);

  container.innerHTML = "";
  container.appendChild(client.getDisplay().getElement());
  
  container.tabIndex = 0;

  client.connect(connectData);

  const display = client.getDisplay();
  let scale = 1;

  
  
  
  
  const mouse = new Guacamole.Mouse(display.getElement());
  mouse.onmousedown = mouse.onmouseup = mouse.onmousemove = (state: any) => {
    const s = new Guacamole.Mouse.State(
      state.x / scale,
      state.y / scale,
      state.left,
      state.middle,
      state.right,
      state.up,
      state.down
    );
    client.sendMouseState(s);
  };
  
  
  
  
  const keyboard = new Guacamole.Keyboard(container);
  keyboard.onkeydown = (k: number) => client.sendKeyEvent(1, k);
  keyboard.onkeyup = (k: number) => client.sendKeyEvent(0, k);
  
  
  const refocus = () => container.focus();
  container.addEventListener("mousedown", refocus);
  container.focus();

  return {
    disconnect() {
      container.removeEventListener("mousedown", refocus);
      keyboard.onkeydown = null;
      keyboard.onkeyup = null;
      if (typeof keyboard.reset === "function") keyboard.reset();
      client.disconnect();
    },
    setScale(s: number) {
      scale = s;
      display.scale(s);
    },
    resize(width: number, height: number) {
      client.sendSize(width, height);
    },
  };
}
