import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:logging/logging.dart';

///firebase 远程参数配置封装
class RemoteConfig {
  ///配置参数
  int get intersFreeLevels => _remoteConfig.getInt('inters_free_levels');
  int get enterIntersFreeDuration => _remoteConfig.getInt('enter_inters_free_duration');
  int get quitIntersFreeDuration => _remoteConfig.getInt('quit_inters_free_duration');
  int get rateUsLevelCount => _remoteConfig.getInt('rate_us_levels_count');
  double get adRevenueThreshold => _remoteConfig.getDouble('ad_revenue_threshold');
  int get bannerFreeDuration => _remoteConfig.getInt('banner_free_duration');

  static final _log = Logger('RemoteConfig');
  RemoteConfig._internal();
  static final RemoteConfig _instance = RemoteConfig._internal();
  factory RemoteConfig() => _instance;

  final _remoteConfig = FirebaseRemoteConfig.instance;

  Future<void> initialize() async {
    await _remoteConfig.setConfigSettings(RemoteConfigSettings(fetchTimeout: const Duration(minutes: 1), minimumFetchInterval: const Duration(hours: 1)));

    ///参数默认值
    await _remoteConfig.setDefaults(const {
      "inters_free_levels": 3, // 新手无插屏广告的levels数，超过此数即可显示插屏
      "enter_inters_free_duration": 5, // 进入游戏插屏广告新手保护时长，单位分
      "quit_inters_free_duration": 3, // 退出游戏插屏广告新手保护时长，单位分
      "rate_us_levels_count": 2, // 用户完成多少个拼图后可以弹出评分框
      "ad_revenue_threshold": 0.01, // 广告累计收益上报阈值，单位美元
      "banner_free_duration": 10, // banner广告新手保护时长，单位分
    });

    _remoteConfig.onConfigUpdated.listen((event) async {
      await _remoteConfig.activate();
      _log.info("remoteConfig update: ${_remoteConfig.getAll().toString()}");
      // Use the new config values here.
    });

    _fetchAndActivate();
  }

  _fetchAndActivate() async {
    _log.info("Firebase remoteConfig fetching...");
    try {
      bool success = await _remoteConfig.fetchAndActivate();
      _log.info("Firebase remoteConfig fetching result: $success}");
    } catch (e) {
      _log.warning("Firebase remoteConfig fetching error: $e");
    }
  }
}
