function updateQuestion() {
  const key = "X0ZcPLZjfDvRN1SsEFzvfGG91iKy4mlQ"
  const sheet = SpreadsheetApp.getActiveSheet();
  const newQuestion = sheet.getRange(5,9).getValue()

  if (sheet.getRange("J11").getValue() == "●  Offline"){
    SpreadsheetApp.getUi().alert("Error: The machine is offline\nTry refreshing if the machine was recently plugged in")
    return;
  }

  if (newQuestion == sheet.getRange(getFirstEmptyRowByColumnArray(sheet)-1, 1).getValue()) {
    Logger.log("Question was already set, skipping");
    return;
  }

  Logger.log("Making Blynk API Request");
  UrlFetchApp.fetch('https://blynk.cloud/external/api/update?token=' + key + "&V10=" + newQuestion);

  sheet.getRange(getFirstEmptyRowByColumnArray(sheet), 1).setValue(newQuestion);
  Logger.log("Update successful");
}

function getFirstEmptyRowByColumnArray(spr) {
  var column = spr.getRange('A:A');
  var values = column.getValues(); // get all data in one call
  var ct = 0;
  while ( values[ct] && values[ct][0] != "" ) {
    ct++;
  }
  return (ct+1);
}

function isWeekdayAndWithinTimeRange() {
  // Generated by Openai GPT-4o

  // Get the active spreadsheet
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  
  // Get the timezone of the spreadsheet
  var timezone = spreadsheet.getSpreadsheetTimeZone();
  
  // Get the current date and time in the spreadsheet's timezone
  var now = new Date();
  var currentDateTime = Utilities.formatDate(now, timezone, 'yyyy-MM-dd HH:mm:ss');
  var currentHour = parseInt(Utilities.formatDate(now, timezone, 'H'), 10);
  var currentDay = Utilities.formatDate(now, timezone, 'E');
  
  // Check if the current day is a weekday (Monday to Friday)
  var isWeekday = (currentDay !== 'Sat' && currentDay !== 'Sun');
  
  // Check if the current time is between 8 AM and 3 PM
  var isWithinTimeRange = (currentHour >= 8 && currentHour < 15);
  
  // Return true if both conditions are met
  return isWeekday && isWithinTimeRange;
}

/**
 * Modifies the machine's question
 * 
 * @param {bool} toggle the button input
 * @param {string} input The value to multiply.
 * @return Response status (OK)
 * @customfunction
 */
function UPDATE_QUESTIONS(toggle, input) {
  if (toggle != true) {
    return "";
  }

  const key = "X0ZcPLZjfDvRN1SsEFzvfGG91iKy4mlQ"

  Logger.log("Making Blynk API Request");
  UrlFetchApp.fetch('https://blynk.cloud/external/api/update?token=' + key + "&V10=" + input);

  return "OK";
}

function onEdit(e){
  if (e.value.toUpperCase() != "TRUE" || e.oldValue.toUpperCase() != "FALSE") {
    return;
  }

  if (e.range.getA1Notation() != "K9") {
    return;
  }

  // updateResponses(); 

  e.source.getActiveSheet().getRange(getFirstEmptyRowByColumnArray(e.source.getActiveSheet()), 1).setValue(e.source.getRange("I5").getValue());

  e.range.setValue("FALSE");
}

function automaticallyUpdateResponses() {
  if (!isWeekdayAndWithinTimeRange()) {
    Logger.log("Failed because out of time range")
    return;
  }
  if (SpreadsheetApp.getActiveSheet().getRange("F4").getValue() == false) {
    Logger.log("Failed because auto-update was off");
    return;
  }

  Logger.log("All checks passed, updating responses...")
  updateResponses();
}

function updateResponses() {
  const sheet = SpreadsheetApp.getActiveSheet();

  const deviceOnline = UrlFetchApp.fetch("https://blynk.cloud/external/api/isHardwareConnected?token=X0ZcPLZjfDvRN1SsEFzvfGG91iKy4mlQ&").getContentText() == "true"
  
  sheet.getRange("J11").setValue("●  " + (deviceOnline ? "Online" : "Offline"));

  if (!deviceOnline) {
    Logger.log("Device offline, not updating");
    return;
  } 
  const data = JSON.parse(UrlFetchApp.fetch("https://blynk.cloud/external/api/get?token=X0ZcPLZjfDvRN1SsEFzvfGG91iKy4mlQ&V0&V1&V2").getContentText())

  sheet.getRange(getFirstEmptyRowByColumnArray(sheet)-1,2,1,3).setValues([Object.values(data)])


  Logger.log("Update successful");
}