/// Created by Haoyi on 2021/7/1

part of "../app_property.dart";

extension IgcPropertyExtension on AppProperty {
  Future<bool> isFirstUseGemsFeature() async {
    final gems = await getInt(PropertyKeys.currentIgcBalance, defValue: -1);
    return gems == -1;
  }

  Future<int> _calculateIgcBalance(int coin) async {
    final bundle = await loadValuesByTag(PropertyTags.igc);
    int currentCoinBalance = bundle.getInt(PropertyKeys.currentIgcBalance) ?? 0;
    final cipher = bundle.getInt(PropertyKeys.currentIgcBalanceValidation) ??
        GuruApp.instance.appSpec.deployment.igcBalanceSecret;
    final cipherCoinBalance = cipher ^ GuruApp.instance.appSpec.deployment.igcBalanceSecret;

    if (cipherCoinBalance != currentCoinBalance) {
      currentCoinBalance = cipherCoinBalance;
    }
    final newBalance = max(currentCoinBalance + coin, 0);
    final updateBundle = PropertyBundle();
    updateBundle.setInt(PropertyKeys.currentIgcBalance, newBalance);
    updateBundle.setInt(PropertyKeys.currentIgcBalanceValidation,
        newBalance ^ GuruApp.instance.appSpec.deployment.igcBalanceSecret);
    setProperties(updateBundle);
    return newBalance;
  }

  Future<int> consumeIgc(int igc) async {
    return await _calculateIgcBalance(-igc);
  }

  Future<int> accumulateIgc(int igc) async {
    return await _calculateIgcBalance(igc);
  }

  Future<bool> clearAllIgc() async {
    return await removeAllWithTag(PropertyTags.igc);
  }

  Future<int> increaseAndGetIapCount() async {
    final count = await getInt(PropertyKeys.iapCount, defValue: 0);
    await setInt(PropertyKeys.iapCount, count + 1);
    return count + 1;
  }

  Future<int> getIapCount() async {
    return await getInt(PropertyKeys.iapCount, defValue: 0);
  }

  Future<bool> isPaidUser() async {
    return (await getIapCount()) > 0;
  }

  Future<int> getIapIgc() async {
    return await getInt(PropertyKeys.iapIgc, defValue: 0);
  }

  Future<int> accumulateIapIgc(int igc) async {
    final accumulatedIgc = await getInt(PropertyKeys.iapIgc, defValue: 0);
    await setInt(PropertyKeys.iapIgc, accumulatedIgc + igc);
    return accumulatedIgc + igc;
  }

  Future<int> getNoIapIgc() async {
    return await getInt(PropertyKeys.noIapIgc, defValue: 0);
  }

  Future<int> accumulateNoIapIgc(int igc) async {
    final accumulatedIgc = await getInt(PropertyKeys.noIapIgc, defValue: 0);
    await setInt(PropertyKeys.noIapIgc, accumulatedIgc + igc);
    return accumulatedIgc + igc;
  }
}
