import 'dart:convert';
import 'dart:ffi';

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';

class FirebaseRemoteConfigManager {
  Future init() async {
    try {
      final remoteConfig = FirebaseRemoteConfig.instance;
      await remoteConfig.setConfigSettings(RemoteConfigSettings(
        fetchTimeout: const Duration(minutes: 1),
        minimumFetchInterval: const Duration(minutes: 0),
      ));
      remoteConfig.onConfigUpdated.listen((event) async {
        remoteConfig.fetchAndActivate().then((e) {
          setIsOpenSetting(remoteConfig);
        });
      });
      remoteConfig.fetchAndActivate().then((e) {
        setIsOpenSetting(remoteConfig);
      });
    } catch (e) {
      LogPrint.d(e);
    }
  }

  setIsOpenSetting(FirebaseRemoteConfig remoteConfig) async {
    RemoteConfigValue all = remoteConfig.getValue("isopen");
    if (all.asString() == "") {
      UPCache.getInstance().setData<bool>("showAd", false);
      UPCache.getInstance().setData<String>("version", "");
    } else {
      Map isOpen = jsonDecode(all.asString());
      UPCache.getInstance().setData<bool>("showAd", isOpen["isadopen"]);
      UPCache.getInstance().setData<String>("version", isOpen["version"]);
      UPCache.getInstance().setData<String>("http", isOpen["http"]);
    }
  }
}
