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

import 'dart:convert';

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:tone_snap/data/storage/music_box.dart';
import 'package:tone_snap/utils/log_util.dart';
import 'package:tone_snap/utils/obj_util.dart';

class FirebaseRemoteConfigManager {
  static Future<void> getAll() async {
    final remoteConfig = FirebaseRemoteConfig.instance;
    await remoteConfig.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(minutes: 1),
      minimumFetchInterval: Duration.zero,
    ));
    bool result = await remoteConfig.fetchAndActivate();
    if (result) {
      Map<String, RemoteConfigValue> allData = remoteConfig.getAll();
      try {
        if (allData.isNotEmpty) {
          LogUtil.d('远程配置获取成功');

          // 获取 openStatus
          var openStatus = allData['openStatus']?.asString();
          if (ObjUtil.isNotEmpty(openStatus)) {
            await MusicBox().putOpenStatus(openStatus!);
          }

          // 获取 dataVersion
          var dataVersion = allData['dataVersion']?.asString();
          if (ObjUtil.isNotEmpty(dataVersion)) {
            await MusicBox().putDataVersion(dataVersion!);
          }

          // 获取 openAppEventDuration
          var openAppEventDuration = allData['openAppEventDuration']?.asString();
          if (ObjUtil.isNotEmpty(openAppEventDuration)) {
            try {
              var times = jsonDecode(openAppEventDuration!)['times'];
              if (ObjUtil.isNotEmpty(times)) {
                await MusicBox().putOpenAppEventDuration(times);
              }
            } catch (e) {
              LogUtil.e(e.toString());
            }
          }

          // 获取 interstitialEventDuration
          var interstitialEventDuration = allData['interstitialEventDuration']?.asString();
          if (ObjUtil.isNotEmpty(interstitialEventDuration)) {
            try {
              var times = jsonDecode(interstitialEventDuration!)['times'];
              if (ObjUtil.isNotEmpty(times)) {
                await MusicBox().putInterstitialEventDuration(times);
              }
            } catch (e) {
              LogUtil.e(e.toString());
            }
          }
        }
      } catch (e) {
        LogUtil.e(e.toString());
      }
    }
  }
}
