const CONFIG_KEY = 'app_config';

/**
 * 默认配置
 * @type {{backendUrl: string, authKey: string, testMode: boolean, stats: {totalDevices: number, onlineDevices: number, lastScan: string}, devices: *[]}}
 */
export const defaultConfig = {
  backendUrl: '',
  authKey: '',
  testMode: false,
  stats: {
    totalDevices: 0,
    onlineDevices: 0,
    lastScan: '',
  },
  devices: [],
};

/**
 * 配置管理工具
 * @type {{load: ((function(): (any))|*), save: ((function(*): (boolean|undefined))|*), clear: ((function(): (boolean|undefined))|*), getConfigPath: (function(): string), isStorageAvailable: ((function(): (boolean|undefined))|*), getStats: (function(): *)}}
 */
const ConfigTool = {
  load: () => {
    try {
      const stored = localStorage.getItem(CONFIG_KEY);
      if (stored) {
        return { ...defaultConfig, ...JSON.parse(stored) };
      }
    } catch (e) {
      console.error('读取配置失败:', e);
      localStorage.removeItem(CONFIG_KEY);
    }
    return { ...defaultConfig };
  },

  /**
   * 保存配置
   * @param config
   * @returns {boolean}
   */
  save: (config) => {
    try {
      localStorage.setItem(CONFIG_KEY, JSON.stringify(config));
      return true;
    } catch (e) {
      console.error('保存配置失败:', e);
      if (e.name === 'QuotaExceededError') {
        alert('存储空间不足，请清理后重试');
      }
      return false;
    }
  },

  /**
   * 清除配置
   * @returns {boolean}
   */
  clear: () => {
    try {
      localStorage.removeItem(CONFIG_KEY);
      return true;
    } catch (e) {
      console.error('清除配置失败:', e);
      return false;
    }
  },

  getConfigPath: () => `localStorage:${CONFIG_KEY}`,

  isStorageAvailable: () => {
    try {
      const testKey = 'test';
      localStorage.setItem(testKey, testKey);
      localStorage.removeItem(testKey);
      return true;
    } catch (e) {
      return false;
    }
  },

  getStats: () => {
    const config = ConfigTool.load();
    return config.stats || { totalDevices: 0, onlineDevices: 0, lastScan: '' };
  },
};

export default ConfigTool;
