
/**
 * factory_dataStorage.js
 * 对 globalThis.factoryTest 的持久化读写
 * 提供三个 API：
 *   setFactoryData(key, value)
 *   getFactoryData(key)
 *   clearFactoryData()
 *
 * 数据落盘文件：product_res.json
 */
const file = require('file.js');

/* ---------- 内部常量 ---------- */
const STORAGE_FILE = 'product_res.json';

/* 13 个工厂测试属性，保持与原有代码一致 */
const KEYS = [
  'color', 'touch', 'wifi', 'sound',
  'uartComm', 'bright', 'licenseAuthor',
  'rtc', 'tvoc', 'burnIn',
  'systemCheck', 'clearAll', 'start','autoStart'
];

function ensureFile() {
  if (file.read(STORAGE_FILE, 'json') === undefined) {
    file.create(STORAGE_FILE);
    file.write(STORAGE_FILE, {});
  }
}

function loadFromDiskOnce() {
  console.log('loadFromDiskOnce');
  if (globalThis.factoryTest !== undefined) return;   // 已装载直接返回
  ensureFile();
  const disk = file.read(STORAGE_FILE, 'json') || {};
  globalThis.factoryTest = {};
  KEYS.forEach(k => {
    globalThis.factoryTest[k] = (disk && disk[k] !== undefined) ? disk[k] : 0;
  });
}
// 把内存快照立即写盘
function flush() {
  ensureFile();
  const toSave = {};
  KEYS.forEach(k => { toSave[k] = globalThis.factoryTest[k]; });
  file.write(STORAGE_FILE, toSave);
}

/* ---------- 对外 API ---------- */
function setFactoryData(key, value) {
  if (!KEYS.includes(key)) throw new Error(`invalid key: ${key}`);
  loadFromDiskOnce();
  globalThis.factoryTest[key] = value;
  flush();
}

function getFactoryData(key) {
  if (!KEYS.includes(key)) throw new Error(`invalid key: ${key}`);
  loadFromDiskOnce();
  return globalThis.factoryTest[key];
}

function clearFactoryData() {
  loadFromDiskOnce();
  KEYS.forEach(k => { globalThis.factoryTest[k] = 0; });
  flush();
}

/* ---------- 模块导出 ---------- */
module.exports = {
  setFactoryData: setFactoryData,
  getFactoryData: getFactoryData,
  clearFactoryData: clearFactoryData,
  loadFromDiskOnce: loadFromDiskOnce,
  KEYS: KEYS
};
