<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Debugger Demo</title>
  <script src="bin/debugger.js"></script>
  <script>
var index = 0;

DebuggerInit({
  locateFile: (file) => '/node_modules/debugger/bin/'+file,
}).ready().then((Debugger) => {
  const surface = Debugger.MakeSWCanvasSurface('debugger_view');
  const player = new Debugger.SkpDebugPlayer();

  // Define an event handler for the file input dialog
  function readSkpFile(e){
    // Did the change event result in the file-input element specifing a file? (user might have cancelled the dialog)
    const file = e.target.files[0];
    if (!file) {
      return;
    }
    // create a callback for when the file finishes being read.
    const reader = new FileReader();
    reader.onload = function(e) {
      // Convert e.target.result (an ArrayBuffer) into a typedarray,
      // otherwise fileMem.set() below seems to have no effect.
      const fileContents = new Uint8Array(e.target.result);
      const size = fileContents.byteLength;
      // Allocate memory in wasm to hold the skp file selected by the user.
      const fileMemPtr = Debugger._malloc(size);
      // Make a typed array view of that memory
      let fileMem = new Uint8Array(Debugger.buffer, fileMemPtr, size);
      // Copy the file into it
      fileMem.set(fileContents);
      // Hand off pointer to wasm
      player.loadSkp(fileMemPtr, size);
    };
    reader.readAsArrayBuffer(file);
  }

  function playFile() {
    interval = Number(document.getElementById('interval').value)
    var intervalID = setInterval(function(){
        if (index < 789){
          player.drawTo(surface, index);
          surface.flush();
          index++;
          console.log("index = "+index);
        }
    }, interval);
  }

  document.getElementById('file-input')
    .addEventListener('change', readSkpFile, false);

  document.getElementById('playbutton')
    .addEventListener('click', playFile, false);

});
  </script>
  </head>
  <body>
    <canvas id=debugger_view width=720 height=1280></canvas>
    <div style="float:right">
      <input type="file" id="file-input" /><br>
      <input type="button" id="playbutton" value="Play" />
      command interval in ms
      <input type="text" id="interval" value="20" />
    <div>
    <div style="float:clear"></div>
  </body>
</html>