// ajax.js
//
// a demo of a client-side javascript site that
// uses (a) libraries and (b) AJAX to fetch remote data.

// I'm using two libraries : jquery and underscore ,
// and have downloaded both of them to this folder ..
//   * jquery 3.6.0 from https://jquery.com/download/
//   * underscore.js 1.31.1 from https://underscorejs.org/ (umd production)
//
// The underscore documentation is at https://underscorejs.org/
//
// The jquery AJAX documentation is at https://api.jquery.com/jquery.ajax/ .
//
// Note that using jquery gives you objects which are wrappers
// around the DOM, with a slightly different API.
// For example compare this jquery code :
//   $('#message').html('test')
// with this vanilla js code :
//   document.getElmentById('message').innerHTML = 'test'
//
// The public remote data source that I'm using is the public API
// for a list of sites that have a public API , described at 
// at https://github.com/davemachado/public-api
//
//   
// Jim Mahoney | cs.bennington.college | Sep 2021 | CC

function ajaxGetEntries(categoryName){
    // get ajax data - list of categories
    // alert("ajaxGetEntry : '" + category + "'");  // debugging

    // We're sending to a url like
    // https://api.publicapis.org/entries?category=name
    // The jquery library will fill in the "?category=name"
    // from the ajax "data:{...}" line.
    
    $.ajax({url: 'https://api.publicapis.org/entries',
	    type: 'GET',
	    data: {category : categoryName}, 
	    dataType: 'json', // parse result & convert to js object
	    success: result => handleAjaxEntries(result),
	    error: function(){$('#message').html('OOPS - entry problem.')},
	   });

    // Don't go to a new page, even though we clicked a link ...
    // if an <a></a> tag has a onclick, and the function returns false,
    // then the link is not followed.
    return false;  
}

function ajaxGetCategories(){
    // get ajax data - one entry 
    // see https://api.jquery.com/jquery.ajax/
    // Note that crossDomain:true is the default for cross domain requests
    $.ajax({url: 'https://api.publicapis.org/categories',
	    type: 'GET',
	    dataType: 'json', // parse result & convert to js object
	    success: result => handleAjaxCategories(result),
	    error: function(){$('#message').html('OOPS -category problem.')},
	   });
}

function callUpdateEntry(category){
    // return string used for calling updateEntry
    return "javascript:ajaxGetEntries('" + category  + "')";
}

function handleAjaxEntries(result){
    // async callback : we just got data for one etry
    // .. so stick it into the web page.
    //alert("handleAjaxEntry : '" + result + '"');
    let entries = $('#entries');
    entries.empty();
    entries.append('<h3> Found ' + result.count + ' results</h3>'); 
    // TO DO : loop over results & summarize ...
    _.each(result.entries,
	   function(entry){
	       entries.append('<div>' +
			      // _.keys(entry) +   // debugging
			      '<a href="' +
			      entry.Link +
			      '">' +
			      entry.Description  +
			      '</a>' + 
			      '</div>'
			     );
	   });
}

function handleAjaxCategories(result){
    // async callback : we just got data listing categories
    // ... so stick it into the web page.

    // DEBUG:
    $('#message').html("<hr>DEBUG : result is <br>" + JSON.stringify(result));
    
    let ul = $('#categoryList');
    ul.empty();   // get rid of any previosly generated list items.
    _.each(result,
	   function(category){
	       //let li = ul.append('<li>' + String(category) + '</li>');
	       let li = ul.append('<li onclick="' +
				  callUpdateEntry(category) +
				  '">' + String(category) + '</li>');
	   });
}

function init(){
    // -- tests --
    // vanilla js :
    //  document.getElementById('message').innerHTML = '* vanilla test *'
    // jquery test :
    //   $('#message').html('* jquery test *');
    // underscore :
    //   $('#message').html(_.map(_.range(2,5), x => x + ":" + 2*x + "<br>"));

    ajaxGetCategories();
}

window.onload = init;