// Delay loading any function until the html dom has loaded. All functions are
// defined in this top level function to ensure private scope.
jQuery(document).ready(function () {

  // Installs error handling.
  jQuery.ajaxSetup({
  error: function(resp, e) {
    if (resp.status == 0){
      alert('You are offline!!\n Please Check Your Network.');
      } else if (resp.status == 404){
        alert('Requested URL not found.');
      } else if (resp.status == 500){
        alert('Internel Server Error:\n\t' + resp.responseText);
      } else if (e == 'parsererror') {
        alert('Error.\nParsing JSON Request failed.');
      } else if (e == 'timeout') {
        alert('Request timeout.');
      } else {
        alert('Unknown Error.\n' + resp.responseText);
      }
    }
  });  // error:function()


  var generate_btn = jQuery('#generate_btn');

  var svg_div = jQuery('#graph_svg_div');
  var graph_data_textarea = jQuery('#graph_data');

  function InsertGraphText(text) {
    graph_data_textarea.val(text);
  }


  function UpdateGraph() {
	svg_div.html("");
    var data = graph_data_textarea.val();
    // Generate the Visualization of the Graph into "svg".
    var svg = "initial svg string is here";
      (async () => {
        // Build the WebAssembly instance.
        const memory = new WebAssembly.Memory({ initial: 2 });
        const response = await fetch('./lenstr.wasm');
        const bytes = await response.arrayBuffer();
        const { instance } = await WebAssembly.instantiate(bytes, {
          env: { memory }
        });

        // Text to copy.
        const text =  graph_data_textarea.val();

        // Configure shared memory.
        const view = new Uint8Array(memory.buffer);
        const pInput = instance.exports.__heap_base;

        encode(view, pInput, text);

        // run our own strlen()
        const bytesCopied = instance.exports.lenstr(pInput);

        console.log('text.length is ', text.length + ' lenstr() says ' + bytesCopied);
      })();

      // Encode string into memory starting at address base.
      const encode = (memory, base, string) => {
        for (let i = 0; i < string.length; i++) {
          memory[base + i] = string.charCodeAt(i);
        }
        memory[base + string.length] = 0;
      };

    svg_div.html("<hr>"+svg);
  }

  // Startup function: call UpdateGraph
  jQuery(function() {
	// The buttons are disabled, enable them now that this script
	// has loaded.
    generate_btn.removeAttr("disabled")
                .text("Generate Graph layout");

  });

  // Bind actions to form buttons.
  generate_btn.click(UpdateGraph);


});
