// -- https://stackoverflow.com/a/39577640
function dataURLtoBlob(dataURL) {
  let array, binary, i, len;
  binary = atob(dataURL.split(",")[1]);
  array = [];
  i = 0;
  len = binary.length;
  while (i < len) {
    array.push(binary.charCodeAt(i));
    i++;
  }
  return new Blob([new Uint8Array(array)], {
    type: "image/png",
  });
}

var p = [];
var cols = 17;
var rows = 17;
var unit = 15; //px
var sw = 0.4; //px
var img;

function setup() {
  var cnv = createCanvas(cols*(unit+sw)+sw, rows*(unit+sw)+sw);
  cnv.parent("p5");
  img = createGraphics(cols*(unit+sw)+sw, rows*(unit+sw)+sw);
  var but = createButton("clear!");
  // var sav = createButton("save!");
  but.class('but').parent("p5");
  // sav.class('sav').parent("p5");
  // createImg("myCanvas.png");
  for (var i = 0; i < cols*rows; i++) {
    p.push(0);
  }
  but.mousePressed(function () {
    for (var i = 0; i < cols*rows; i++) {
      p.push(0);
    }
    img.clear();
  });
}

function draw() {
  //
  background(255);
  
  //draw the grid
  stroke(127);
  strokeWeight(sw);
  for (var c = 0; c < cols; c++) {
    for (var r = 0; r < rows; r++) {
      noFill();
      rect(c*(unit+sw)+sw, r*(unit+sw)+sw, unit, unit);
    }
  }
  
  //
  image(img, 0, 0);
  
  //pointer
  fill(0, 255, 0);
  strokeWeight(0);
  circle(mouseX, mouseY, 10);
  
  //
  if (mouseIsPressed && mouseButton === LEFT) {
    //find slot under the pointer
    var mouseC = int(mouseX/(unit+sw));
    var mouseR = int(mouseY/(unit+sw));
    if (mouseC < cols && mouseR < rows) p[mouseC*cols + mouseR] = 1;
    img.strokeWeight(0);
    img.fill(0);
    img.rect(mouseC*(unit+sw), mouseR*(unit+sw), unit+sw*2, unit+sw*2);
  }
}

function submitForm(event) {
  //
  var that = event.target.elements;
  
  //
  var fd = new FormData();
  
  //
  fd.append("audiofile", that.audiofile.files[0]);
  
  //
  var dataurl = img.elt.toDataURL();
  var pixels = dataURLtoBlob(dataurl);
  fd.append("pixels", pixels, "pixels.png");
  
  //
  fd.append("message", that.message.value);
  
  //
  var request = new XMLHttpRequest();
  request.open("POST", "/");
  request.send(fd);
  
  //
  event.preventDefault();
}

const form = document.getElementById('form');
form.addEventListener('submit', submitForm);

/* global  describe describeElement textOutput gridOutput print frameCount deltaTime focused cursor frameRate noCursor displayWidth displayHeight windowWidth windowHeight windowResized width height fullscreen pixelDensity displayDensity getURL getURLPath getURLParams alpha blue brightness color green hue lerpColor lightness red saturation Color background clear colorMode fill noFill noStroke stroke erase noErase arc ellipse circle line point quad rect square triangle ellipseMode noSmooth rectMode smooth strokeCap strokeJoin strokeWeight bezier bezierDetail bezierPoint bezierTangent curve curveDetail curveTightness curvePoint curveTangent beginContour beginShape bezierVertex curveVertex endContour endShape quadraticVertex vertex normal plane box sphere cylinder cone ellipsoid torus Geometry loadModel model HALF_PI PI QUARTER_PI TAU TWO_PI DEGREES RADIANS preload setup draw remove disableFriendlyErrors noLoop loop isLooping push pop redraw p5 Element select selectAll removeElements changed input createDiv createP createSpan createImg createA createSlider createButton createCheckbox createSelect createRadio createColorPicker createInput createFileInput createVideo createAudio VIDEO AUDIO createCapture createElement MediaElement File Graphics createCanvas resizeCanvas noCanvas createGraphics blendMode drawingContext setAttributes applyMatrix resetMatrix rotate rotateX rotateY rotateZ scale shearX shearY translate storeItem getItem clearStorage removeItem createStringDict createNumberDict TypedDict NumberDict append arrayCopy concat reverse shorten shuffle sort splice subset float int str boolean byte char unchar hex unhex join match matchAll nf nfc nfp nfs split splitTokens trim deviceOrientation accelerationX accelerationY accelerationZ pAccelerationX pAccelerationY pAccelerationZ rotationX rotationY rotationZ pRotationX pRotationY pRotationZ turnAxis setMoveThreshold setShakeThreshold deviceMoved deviceTurned deviceShaken keyIsPressed key keyCode keyPressed keyReleased keyTyped keyIsDown movedX movedY mouseX mouseY pmouseX pmouseY winMouseX winMouseY pwinMouseX pwinMouseY mouseButton mouseIsPressed mouseMoved mouseDragged mousePressed mouseReleased mouseClicked doubleClicked mouseWheel requestPointerLock exitPointerLock touches touchStarted touchMoved touchEnded createImage saveCanvas saveFrames Image loadImage image tint noTint imageMode pixels blend copy filter get loadPixels set updatePixels loadJSON loadStrings loadTable loadXML loadBytes httpGet httpPost httpDo XML createWriter PrintWriter save saveJSON saveStrings saveTable Table TableRow day hour minute millis month second year abs ceil constrain dist exp floor lerp log mag map max min norm pow round sq sqrt fract createVector Vector noise noiseDetail noiseSeed randomSeed random randomGaussian acos asin atan atan2 cos sin tan degrees radians angleMode textAlign textLeading textSize textStyle textWidth textAscent textDescent textWrap loadFont text textFont Font orbitControl debugMode noDebugMode ambientLight specularColor directionalLight pointLight lights lightFalloff spotLight noLights loadShader createShader shader resetShader texture textureMode textureWrap normalMaterial ambientMaterial emissiveMaterial specularMaterial shininess Shader camera perspective ortho frustum createCamera Camera setCamera

LEFT RIGHT CENTER

<<<_p5_keywords

*/
