const { UserColors } = require("./UserColors.js");

class GhostOverlays {
  constructor(graph, userColors, cursorHref) {
    // this.userNames = userNames;
    this.userColors = userColors;
    this.canvas = graph.view.canvas;
    this.svg = this.canvas.parentElement;
    this.cursorHref = cursorHref;

    this.map = new Map();
  }

  // Update or create ghost cursor. Idempotent.
  put(userId, name, x, y) {
    let state = this.map.get(userId);
    if (state === undefined) {
      const g = document.createElementNS("http://www.w3.org/2000/svg", 'g');
      const image = document.createElementNS("http://www.w3.org/2000/svg", 'image');
      const text = document.createElementNS("http://www.w3.org/2000/svg", 'text');
      text.style.fontSize = "10px";
      text.style.fill = this.userColors.getColor(userId);
      text.setAttribute('y', 30);
      const textNode = document.createTextNode("");
      text.appendChild(textNode);
      image.setAttribute('href', this.cursorHref);
      image.setAttribute('width', 11.6);
      image.setAttribute('height', 18.2);
      g.appendChild(image);
      g.appendChild(text);
      this.canvas.appendChild(g);
      const transform = this.svg.createSVGTransform();
      g.transform.baseVal.appendItem(transform);
      state = {transform, textNode, timeout: null};
      this.map.set(userId, state);
    }
    state.transform.setTranslate(
      (x + graph.view.translate.x) * graph.view.scale,
      (y + graph.view.translate.y) * graph.view.scale,
    );
    state.textNode.data = name;
    if (state.timeout) {
      clearTimeout(state.timeout);
    }
    state.timeout = setTimeout(() => state.transform.setTranslate(-50, -50), 5000);
  }
}

module.exports = { GhostOverlays };