import { oncePromiseResolve } from '../utils/call';
export default class LogLevelManager {
  constructor({ loggers, localStorage }) {
    this._loggers = loggers;
    this._storage = localStorage;
    this._skey = 'sys_log_config';
    this._stemp = null;
    this._init();
  }

  /**
   * 初始化
   */
  _init() {
    try {
      this._getStorage = oncePromiseResolve(async () => {
        return (await this._storage.getItem(this._skey) || {});
      });
      // 设置日志实例获取缓存信息
      (this._loggers || []).forEach(logger => {
        logger && logger.setStorageConfig(this.getConfig.bind(this))
      });
    } catch (err) {
      console.warn('init loglevel fail', err);
    }
  }

  /**
   * @typedef {Object} Config
   * @property {number} level 日志上报等级
   * @property {number} printLevel 日志打印等级
   */
  /**
   * 设置日志配置
   * @param {Config} config 
   */
  async setConfig(config) {
    if (!config) return false;

    const loggers = this._loggers || [];
    if (!loggers.length) return false;
    this._stemp = Object.assign((this._stemp || {}), config);
    loggers.map(logger => logger && logger.setConfig(this._stemp));
    try {
      await this._storage.setItem(this._skey, this._stemp);
    } catch (err) {
      // console.warn
    }
    return true;
  }

  /**
   * 获取配置信息
   * @returns 
   */
  async getConfig() {
    if (!this._stemp) {
      try {
        this._stemp = await this._getStorage();
      } catch (err) {
        return null
      }
    }
    return this._stemp;
  }
}