//how do we get information loaded to from the server?
var nameInput;
var scoreInput;

function setup(){
    //createCanvas(400,400);
    //background(51);
    //access that file on the server with a simple loadJSON to that path
    //loadJSON('all',gotData);
    
    var button = select('#submit');
    button.mousePressed(submitData);
    nameInput = select('#name');
    scoreInput = select('#score');
    //call the function to draw the initial data
    drawData();
}

function drawData(){
    //just so we have a function to draw our data to the canvas that we can redo when we get more data
    loadJSON('all',gotData);
}

function gotData(data){

    //background(51);
    console.log(data);
    //console.log(typeof(data));//this should return "object"
    //this serves back an object.  it's not an array.
    //make it into an array so it can be sorted with .sort().
    var scoreSortArray = Object.entries(data);
    console.log(scoreSortArray);
    scoreSortArray.sort(function(a, b) {
        //sort it, descending order
        return b[1] - a[1];
    });
    console.log(scoreSortArray);
    //now that it's an array we can also traverse it because it has a .length
    //seletc the <ul id="scores"> from the html doc.
    var scoresUL = select('#scores');
    for(var i=0;i<scoreSortArray.length;i++){
        //this is an array of arrays now.  Name is at the 0 position, score is at the 1 position
      var name = scoreSortArray[i][0];
      var score = scoreSortArray[i][1];
      var liEntry = createElement('li');
      liEntry.html(name + ': ' + score);
      liEntry.parent(scoresUL);
      
    }
    
    //Another way to work with this object would be to just grab the keys, and in this case you'd traverse it by key
    //grab the keys - the object is a series of key-value pairs
    
    //var keys = Object.keys(data);
    //console.log(keys);//gives you an array of keys
    /*myDiv = createDiv();
    myDiv.id('scores')
    for(var i=0;i<keys.length;i++){
        //the name is the key
        var name = keys[i];
        //score is the value of the key, what's the value at each name?
        var score = data[name];
        var newP = createP(name + ': ' + score);
        newP.parent('scores');
    }*/
}

//what happens when we hit submit button?
function submitData(){
    //get the data
    var name = nameInput.value();
    var score = scoreInput.value();
    //well here we're using a get request to send data with loadJSON
    loadJSON('add/' + name + '/' + score, finished);
    function finished(data){
        console.log(data);
        //draw the canvas again
        clearTheP();//clear that div out
        drawData();
    }
}

function clearTheP(){
    //remove with vanilla js because it's just easier and more reliable.
    var scoresUL = document.getElementById('scores');
    //console.log(scoresUL);
    var listLength = scoresUL.children.length;

    for (i = 0; i < listLength; i++) {
    scoresUL.removeChild(scoresUL.children[0]);
  }
}
    
