/* global XMLHttpRequest, expect */

function loadBinaryResource (url, unicodeCleanUp) {
  const req = new XMLHttpRequest()
  req.open('GET', url, false)
   // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null)
  if (req.status !== 200) {
    throw new Error('Unable to load file')
  }
      var responseText = req.responseText;
    var responseTextLen = req.responseText.length;
    if (unicodeCleanUp === true) {
      var binary = ''
      for (var j = 0; j < responseTextLen; j+=1) {
          binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
      }
      var base64data = window.btoa(binary);
      return window.atob(base64data);
    }
  return req.responseText;
}

function sendReference (filename, data) {
  const req = new XMLHttpRequest()
  req.open('POST', `http://localhost:9090/${filename}`, true)
  req.onload = e => {
    console.log(e)
  }
  req.send(data)
}

const resetCreationDate = input =>
  input.replace(
    /\/CreationDate \(D:(.*?)\)/,
    '/CreationDate (D:19871210000000+00\'00\'\)'
  )

/**
 * Find a better way to set this
 * @type {Boolean}
 */
window.comparePdf = (actual, expectedFile, suite, unicodeCleanUp) => {
  let pdf;
  unicodeCleanUp = unicodeCleanUp || false;
  try {
    pdf = loadBinaryResource(`/base/tests/${suite}/reference/${expectedFile}`, unicodeCleanUp)
  } catch (error) {
    sendReference(`/tests/${suite}/reference/${expectedFile}`, resetCreationDate(actual))
    pdf = actual
  }
  const expected = resetCreationDate(pdf).trim()
  actual = resetCreationDate(actual.trim())

  expect(actual).toEqual(expected)
}

@@ -526,45 +526,123 @@
 ar b
-inar
+yteArra
 y = 
-''
+%5B%5D;
 %0A      
-for (var j
+let asciidDecoder = new TextDecoder('iso-8859-1');%0A      var i = 0;%0A      for (i
  = 0; 
-j
+i
  %3C 
+req.
 resp
@@ -653,16 +653,22 @@
 Text
-Len; j
+.length; i 
 +=
+ 
 1) %7B
@@ -680,40 +680,27 @@
     
-  binary += String.fromCharCode(
+byteArray.push(req.
 resp
@@ -723,9 +723,9 @@
 eAt(
-j
+i
 ) & 
@@ -729,16 +729,17 @@
  & 0xff)
+;
 %0A      %7D
@@ -749,81 +749,61 @@
     
-var base64data = window.btoa(binary);%0A      return window.atob(base64data
+return asciidDecoder.decode(new Uint8Array(byteArray)
 );%0A 

Update compare.js