import startTic80 from "./tic80.js";

const initialize = () => {
  const canvasSelector = "#canvas";
  const canvasElement = document.querySelector(canvasSelector);

  const options = {
    canvas: canvasElement,

    arguments: ["/tic80/cart.tic"],

    saveAs(blob, filename) {
      const url = URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = url;
      link.download = filename;

      link.click();
    },

    showAddPopup(callback) {
      callback(null, null);
      var input = document.createElement("input");
      input.type = "file";
      input.click();
      input.addEventListener("change", (event) => {
        const file = event.target.files[0];
        if (file) {
          var reader = new FileReader();
          reader.onload = function (event) {
            var rom = new Uint8Array(event.target.result);
            callback(file.name, rom);
          };
          reader.readAsArrayBuffer(file);
        }
      });
    },

    preRun: [
      function (module) {
        module.ENV.SDL_EMSCRIPTEN_KEYBOARD_ELEMENT = canvasSelector;
      }
    ]
  };

  startTic80(options);
}

const a = () => {
  initialize();
  document.querySelector("#canvas").removeEventListener("click", a);
  document.querySelector("#deez-nuts").remove();
}

document.querySelector("#canvas").addEventListener("click", a);
