// Author: fengshengxiong
// Date: 2024/6/26
// Description: firebase_remote_config管理

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter_translate/ads/interstitial_ad_manage.dart';
import 'package:flutter_translate/common/hive/remote_config_box.dart';
import 'package:flutter_translate/common/utils/log_utils.dart';
import 'package:flutter_translate/common/utils/obj_util.dart';
import 'package:package_info_plus/package_info_plus.dart';

class FirebaseRemoteConfigManager {
  static Future<void> getAll() async {
    try {
      final remoteConfig = FirebaseRemoteConfig.instance;
      await remoteConfig.setConfigSettings(RemoteConfigSettings(
        fetchTimeout: const Duration(seconds: 15),
        minimumFetchInterval: Duration.zero,
      ));
      bool result = await remoteConfig.fetchAndActivate();
      if (result) {
        Map<String, RemoteConfigValue> allData = remoteConfig.getAll();
        if (allData.isEmpty) {
          Log.d('远程配置为空');
          return;
        }
        Log.d('远程配置获取成功');
        // 获取 isopen
        var isOpen = allData['isopen']?.asString();
        if (ObjUtil.isNotEmpty(isOpen)) {
          await RemoteConfigBox().putIsOpen(isOpen!);

          final packageInfo = await PackageInfo.fromPlatform();
          if (RemoteConfigBox().getVersion() != packageInfo.version) {
            await RemoteConfigBox().putAdSwitch(true);
            InterstitialAdManager().loadAllAd();
          }
        }
      }
    } catch (e) {
      Log.d(e.toString());
    }
  }
}
