const loadMain = src => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.onload = resolve
    script.onerror = reject
    script.src = "https://cdn.jsdelivr.net/npm/butterchurn@latest/lib/" + src
    document.head.append(script)
  })
}

const loadPreset = src => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.onload = resolve
    script.onerror = reject
    script.src = "https://cdn.jsdelivr.net/npm/butterchurn-presets@latest/lib/" + src
    document.head.append(script)
  })
}

function initMilkdrop() {
  return new Promise((resolve, reject) => {
    Promise.all([
        loadMain("butterchurn.min.js"),
        loadMain("butterchurnExtraImages.min.js"),
        loadPreset("butterchurnPresets.min.js"),
        loadPreset("butterchurnPresetsExtra.min.js"),
        loadPreset("butterchurnPresetsExtra2.min.js"),
      ])
      .then(resolve)
      .catch(e => {
        console.log("Script Loading Error", e);
        reject(e);
      });
  });
}

window['libopenmpt'] = {};
libopenmpt.onRuntimeInitialized = function() {
  window.player = new ChiptuneJsPlayer(new ChiptuneJsConfig(-1));

  initMilkdrop().then(function() {
    window.visualizer = butterchurn.default.createVisualizer(player.audioContext, canvas, {
      width: canvas.width,
      height: canvas.height
    });

    visualizer.loadExtraImages(butterchurnExtraImages.default.getImages());

    const presets = {};
    Object.assign(presets, butterchurnPresets.getPresets());
    Object.assign(presets, butterchurnPresetsExtra.getPresets());
    Object.assign(presets, butterchurnPresetsExtra2.getPresets());
    visualizer.loadPreset(presets["444"], 0.0);

    var select = document.getElementById("preset");
    for (const preset of Object.keys(presets)) {
      var option = document.createElement("option");
      option.value = option.innerText = preset;
      if (preset == "444")
        option.selected = true;
      select.appendChild(option);
    }
    select.addEventListener("change", function() {
      visualizer.loadPreset(presets[select.value], 0.0);
    })

    function animate() {
      visualizer.render();
      requestAnimationFrame(animate);
    }

    animate();
  })

  player.load("assets/ACCESSiON - Cyberzerk intro.xm").then(buffer => {
    window.playTunes = function() {
      if (!player.currentPlayingNode) {
        player.play(buffer);
        player.currentPlayingNode.paused = true;
        visualizer.connectAudio(player.currentPlayingNode);
      }
      player.togglePause();
      playbutton.innerText = player.currentPlayingNode.paused ? "▶️" : "⏸";
    }
  });
  player.addHandler('onRowChange', () => {
    progress.style.width = `${((player.position() % player.duration()) / player.duration()) * 100}%`;
  });
}

function keygen() {
  fetch(`https://sponsor.ajay.app/api/generateToken/free?key=${Date.now()}`).then(r => r.json()).then(d => {
    document.getElementById("key").value = d.licenseKey;
  });
}