var now = new Date();
var today = Utilities.formatDate(now, 'America/New_York', 'MM/dd/yyyy');
const readSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
const writeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];

// This function needs to happen every time the script runs.
function writeHeadings() {
  // Write the new Column Headings
  var lastColumn = writeSheet.getLastColumn()+1;
  var lastRow = writeSheet.getLastRow();
  writeSheet.getRange(1, lastColumn).setValue("Percent Change");
  writeSheet.getRange(1, lastColumn+1).setValue("Progress");
  writeSheet.getRange(2, lastColumn+1).setValue(today);
  addProgress(lastColumn);
}

// This function takes the progress from Column D of Sheet0 and adds it to Sheet1
function addProgress(lastColumn, prevColumn) {
  // Process Data from Sheet0
  var numRows = readSheet.getLastRow()-1;   // Number of rows to process
  var dataRange = readSheet.getRange(2, 2, numRows, 3);
  // Process First Row from Sheet1
  // var numRows = writeSheet.getLastRow()-1;   // Number of rows to process
  // var dataRange = writeSheet.getRange(3, 1, numRows, 1);
  var values = dataRange.getValues();

  for (item in values) {
    var row = values[item];
    var course= row[0];
    var avgProgress = row [2];
    findRow(course, avgProgress, lastColumn);
  }
}

function findRow(course, avgProgress, lastColumn) {
  var prevColumn = writeSheet.getLastColumn()-2;
  var numRows = writeSheet.getLastRow();
  var data = writeSheet.getRange(3,1,numRows,1).getValues();
  var progArray = [];
  progArray.push(avgProgress);
  for(var i = 0; i<data.length;i++){
    if(data[i][0] == course){
      var row = i+3;
      var prevVal = writeSheet.getRange(row, prevColumn).getValues();
      writeSheet.getRange(row, lastColumn+1).clearFormat();
      writeSheet.getRange(row, lastColumn).clearFormat();
      writeSheet.getRange(row, lastColumn+1).setValue(avgProgress);
      writeSheet.getRange(row, lastColumn).setValue(percentDiff(prevVal, avgProgress));
    }
  }
  // writeSheet.getRange(numRows, 1).setValue("Average Progress across all Courses");
  // writeSheet.getRange(numRows, lastColumn+1).setValue(formulaAverage);
}

function percentDiff(prevVal, avgProgress){
  var prevVal = prevVal-0
  var avgProgress = avgProgress-0
  var percentChange = percentChange-0
  // This block will NOT show negative changes. So if a number decreases from one week to the next, it will still show a POSITIVE % change.
  // var percentChange =
  //   (
  //     (Math.abs(prevVal-avgProgress))/((prevVal+avgProgress)/2)
  //   )
  // return percentChange

  // Business Math! This will show negativos.
  var percentChange =
    (
      (avgProgress-prevVal)/(prevVal)
    )
  return percentChange
}