import { Conductor } from "./conductor";

export class Renderer {
  timeIndicator;
  currStaveNumber;
  numStaves;
  sheetWindow;

  constructor() {
    this.numStaves = 6;
    this.currStaveNumber = 1;
    this.timeIndicator = document.querySelector("#time-indicator");

    this.timeIndicator.addEventListener("animationiteration", () => {
      this.currStaveNumber++;
      if (this.currStaveNumber > this.numStaves) {
        this.cleanUpAndRestart();
      }
    });

    this.sheetWindow = document.getElementById("music-window");

    for (let i = 1; i <= this.numStaves; i++) {
      const staveWrapper = document.createElement("div");
      staveWrapper.classList.add("stave-wrapper");
      staveWrapper.setAttribute("id", `stave-wrapper-${i}`);
      staveWrapper.style.position = "relative";

      const staveObject = document.createElement("object");
      staveObject.type = "image/svg+xml";
      staveObject.data = "assets/svg/stave.svg";
      staveObject.classList.add("stave-svg");

      staveWrapper.appendChild(staveObject);
      this.sheetWindow.appendChild(staveWrapper);
    }
  }

  placeIcon = (instrument) => {
    if (this.currStaveNumber > this.numStaves) this.currStaveNumber = 1;

    const targetWrapper = document.getElementById(
      `stave-wrapper-${this.currStaveNumber}`
    );

    const rect = this.timeIndicator.getBoundingClientRect();
    const sheetLeft = this.sheetWindow.getBoundingClientRect().left;
    const xPosition = rect.left + window.scrollX - sheetLeft;

    const newObject = document.createElement("div");
    newObject.classList.add("event-icon");
    newObject.style.position = "absolute";
    newObject.style.left = `${
      xPosition - document.documentElement.clientWidth / 200
    }px`;
    newObject.style.top = `${instrument.yPos}`;

    const eventIcon = document.createElement("object");
    eventIcon.type = "image/svg+xml";
    eventIcon.data = instrument.image;

    newObject.appendChild(eventIcon);
    targetWrapper.appendChild(newObject);
  };

  cleanUpAndRestart(reload = false) {
    const icons = document.querySelectorAll(".event-icon");
    this.timeIndicator = document.getElementById("time-indicator");

    icons.forEach((icon) => {
      icon.classList.add("fade-out");
      icon.addEventListener("transitionend", () => {
        icon.remove();
      });
    });

    this.currStaveNumber = 1;

    Conductor.setTitle();

    if (reload) location.reload();
  }
}
