import { sendMidiMessage } from "./midi.js";
import { Conductor } from "./conductor.js";
import { DataStream } from "./socket.js";
import { Renderer } from "./render.js";

document.addEventListener("DOMContentLoaded", async () => {

  const midiAccess = await navigator.requestMIDIAccess();
  const conductor = new Conductor();
  await conductor.init();
  const dataStream = new DataStream();
  const instruments = await conductor.instruments;
  let strikes = 0;
  const strikeEvery = 2;


  const renderer = new Renderer();

  dataStream.addEventListener("strike", () => {
    console.log(strikes);
    //** select instrument */
    if (strikes === strikeEvery){

      const keys = Object.keys(instruments);
      const randomIndex = Math.floor(Math.random() * keys.length);
      const selectedInstrument = instruments[keys[randomIndex]];
  
      //** select sample */
      const numSamples = selectedInstrument.numSamples;
      const randomSampleNumber = Math.floor(Math.random() * numSamples);
  
      renderer.placeIcon(selectedInstrument);
      sendMidiMessage(selectedInstrument.midiChannelName, randomSampleNumber + 1, midiAccess);
      strikes = 0;
    }
    strikes++;
  });

  dataStream.init();

  conductor.showMainContent();
});
