//-----------------------------------------------
//V 2.00
//  05/12/2025
//  Migrate to V8 from ES5(Rhino)
//  fix a bug in clearLog() generate error messages
//
//V 1.10
//  04/26.2023
//  add script lock and check
//  add customer field parse to column process
//
//V 1.00
//  2018
//-----------------------------------------------
// Format a string into text for the HTML response
function out(s) {
  return ContentService.createTextOutput(s).setMimeType(ContentService.MimeType.TEXT);
}

function doPost(e) {
  const props = PropertiesService.getScriptProperties();
  const ssID = props.getProperty('targetSpreadsheetID');

  if (!ssID) return out("Property targetSpreadsheetID not found. Be sure to run Setup script.");

  const lock = LockService.getScriptLock();
  try {
    lock.waitLock(30000);
  } catch (ex) {
    Logger.log('Could not obtain lock after 30 seconds.');
    return HtmlService.createHtmlOutput("<b>Server Busy. Please try after some time.</b>");
  }

  const ss = SpreadsheetApp.openById(ssID);
  if (!ss) {
    lock.releaseLock();
    return out(`Could not find spreadsheet ID [${ssID}]. Aborting.`);
  }

  const sheetName = props.getProperty('targetSheetName');
  if (!sheetName) {
    lock.releaseLock();
    return out("Property targetSheetName not found. Be sure to run Setup script.");
  }

  const sheet = ss.getSheetByName(sheetName);
  if (!sheet) {
    lock.releaseLock();
    return out(`Could not find sheet named [${sheetName}]. Aborting.`);
  }

  const parameters = e.parameter;
  let headers = [];

  if (sheet.getLastColumn() !== 0) {
    headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
  }

  let newHeadersFlag = false;
  const newRow = [];

  for (const p in parameters) {
    if (p !== "Custom Fields") {
      let col = headers.indexOf(p);
      if (col < 0) {
        headers.push(p);
        col = headers.indexOf(p);
        newHeadersFlag = true;
      }
      newRow[col] = parameters[p];
    } else {
      const cfstr = parameters[p];
      Logger.log(`cfstr=${cfstr}`);

      if (cfstr && cfstr.length >= 2) {
        const cfsss = cfstr.split(",");
        cfsss.forEach((entry, i) => {
          if (entry.includes(":")) {
            const [key, value] = entry.split(":");
            let colcf = headers.indexOf(key);
            if (colcf < 0) {
              headers.push(key);
              colcf = headers.indexOf(key);
              newHeadersFlag = true;
            }
            newRow[colcf] = value;
          } else {
            const cfvalue = entry.trim();
            if (cfvalue.length >= 1) {
              const cflabel = `Field ${i + 1}`;
              let colcf = headers.indexOf(cflabel);
              if (colcf < 0) {
                headers.push(cflabel);
                colcf = headers.indexOf(cflabel);
                newHeadersFlag = true;
              }
              newRow[colcf] = cfvalue;
            }
          }
        });
      }
    }
  }

  if (newRow.length === 0) return out("No parameters found, no data appended.");

  if (newHeadersFlag) {
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
  }

  sheet.appendRow(newRow);
  lock.releaseLock();
  return out("Data appended successfully.");
}

function doGet(e) {
  return doPost(e);
}

function setupLoggingToCurrentSheet() {
  const props = PropertiesService.getScriptProperties();
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  props.setProperty('targetSpreadsheetID', sheet.getId());
  props.setProperty('targetSheetName', sheet.getActiveSheet().getSheetName());
}

function clearLog() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const last = sheet.getLastRow();
  if (last > 1) sheet.deleteRows(2, last - 1);
}

function onOpen() {
  SpreadsheetApp.getActive().addMenu("V9 Script", [
    { name: "Activate log", functionName: "setupLoggingToCurrentSheet" },
    { name: "Clear log", functionName: "clearLog" }
  ]);
}