import 'package:guru_app/financial/asset/assets_model.dart';
import 'package:guru_app/financial/asset/assets_store.dart';
import 'package:guru_app/financial/iap/iap_manager.dart';
import 'package:guru_app/financial/iap/iap_model.dart';
import 'package:guru_app/financial/igb/igb_manager.dart';
import 'package:guru_app/financial/igc/igc_manager.dart';
import 'package:guru_app/financial/reward/reward_manager.dart';
import 'package:guru_utils/extensions/extensions.dart';

/// Created by Haoyi on 2021/7/2

class FinancialManager {
  static final FinancialManager instance = FinancialManager._();

  FinancialManager._();

// final RewardAssetService rewardService;

  Stream<AssetsStore<Asset>> get observableAssets => Rx.combineLatest3<AssetsStore<Asset>,
              AssetsStore<Asset>, AssetsStore<Asset>, AssetsStore<Asset>>(
          IapManager.instance.observableAssetStore,
          IgcManager.instance.observableAssetStore,
          RewardManager.instance.observableAssetStore, (iapPurchased, gemAssets, rewarded) {
        return _merge(iapPurchased: iapPurchased, gemAssets: gemAssets, rewarded: rewarded);
      });

  AssetsStore<Asset> get currentAssets => _merge(
      iapPurchased: IapManager.instance.purchasedStore,
      gemAssets: IgcManager.instance.purchasedStore,
      rewarded: RewardManager.instance.rewardedStore);

  static AssetsStore<Asset> _merge(
      {required AssetsStore<Asset> iapPurchased,
      required AssetsStore<Asset> gemAssets,
      required AssetsStore<Asset> rewarded}) {
    final result = AssetsStore<Asset>();
    if (iapPurchased.isActive) {
      iapPurchased.forEach((productId, possessions) {
        result.addAsset(possessions);
      });
    }
    if (gemAssets.isActive) {
      gemAssets.forEach((productId, possessions) {
        result.addAsset(possessions);
      });
    }
    if (rewarded.isActive) {
      rewarded.forEach((productId, possessions) {
        result.addAsset(possessions);
      });
    }
    return result;
  }

  void init() {
    IapManager.instance.init();
    IgcManager.instance.init();
    IgbManager.instance.init();
    RewardManager.instance.init();
  }

  void switchSession(String fromUid, String toUid) {
    IapManager.instance.switchSession();
    IgcManager.instance.switchSession();
    RewardManager.instance.switchSession();
  }
}
