function doGet(e) {
  return HtmlService.createHtmlOutput("get request received");
}

//this is a function that fires when the webapp receives a POST request
function doPost(e) {
  var params = JSON.stringify(e.postData.contents);
  params = JSON.parse(params);
  var now = new Date();
  var timeAdded = Utilities.formatDate(now,'America/New_York','MM/dd/yyyy');

  var learnerName = params.substring(params.indexOf('{"name":"') + 7, params.lastIndexOf('"email"'));
  learnerName = learnerName.slice(learnerName.indexOf('"') + 1, learnerName.lastIndexOf('"'),);
  //Logger.log("Name = " + learnerName);

  var learnerEmail = params.substring(params.indexOf('"sso_uid":"') + 9, params.lastIndexOf('"full_name"'));
  learnerEmail = learnerEmail.slice(learnerName.indexOf('"') + 3, learnerEmail.lastIndexOf('"'),);
  //Logger.log("Email = " + learnerEmail);

  var courseName = params.substring(params.indexOf('"course_name":') + 4, params.lastIndexOf('}},{"id"'));
  courseName = courseName.slice(courseName.indexOf('"') + 3, courseName.lastIndexOf('"'),);
  //Logger.log("Course = " + courseName);

  var activityName = params.substring(params.indexOf('"title":"') + 4, params.lastIndexOf('"course_name"'));
  activityName = activityName.slice(activityName.indexOf('"') + 3, activityName.lastIndexOf('"'),);
  //Logger.log("Activity = " + activityName);

  var quizScore = params.substring(params.indexOf('"value":') + 8, params.lastIndexOf(',"created_at"'));
  //quizScore = quizScore.slice(quizScore.indexOf('"') + 3, quizScore.lastIndexOf('"'),);
  //Logger.log("Quiz Score = " + quizScore);

  var dateCompleted = params.substring(params.indexOf('"updated_at":"') + 4, params.lastIndexOf('"activated_at"'));
  dateCompleted = dateCompleted.slice(dateCompleted.indexOf('"') + 3, dateCompleted.lastIndexOf('"'),);
  var localTime = new Date(dateCompleted);
  localTime = localTime.toString();
  localTime = localTime.slice(0,localTime.indexOf(' GMT'));
  //dateCompleted = dateCompleted.toString();
  //Logger.log("Completed on = " + dateCompleted);
  
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = Math.max(sheet.getLastRow(),1);

  sheet.insertRowAfter(lastRow);
  sheet.getRange(lastRow + 1, 1).setValue(timeAdded);
  sheet.getRange(lastRow + 1, 2).setValue(learnerName);
  sheet.getRange(lastRow + 1, 3).setValue(learnerEmail);
  sheet.getRange(lastRow + 1, 4).setValue(courseName);
  sheet.getRange(lastRow + 1, 5).setValue(activityName);
  sheet.getRange(lastRow + 1, 6).setValue(localTime);
  sheet.getRange(lastRow + 1, 7).setValue(quizScore+"%");
  sheet.getRange(lastRow + 1, 8).setValue(params);


  SpreadsheetApp.flush();
  return HtmlService.createHtmlOutput("post request received");
}