import 'mmkv_util.dart';

class PrivacyCompliance {
  PrivacyCompliance._();

  static const String isPolicyGranted = 'isPolicyGranted';
  static final List<EnsurePolicyGrant> _pendingTasks = [];
  static bool _isPolicyGranted = false;

  static Future<void> ensurePolicyGranted(EnsurePolicyGrant ensure) async {
    if (isAgreePrivacyPolicy()) {
      await ensure.onPolicyGrant();
    } else {
      _pendingTasks.add(ensure);
    }
  }

  static Future<void> setPrivacyPolicy(bool isAgree) async {
    final bool oldValue = isAgreePrivacyPolicy();
    if (isAgree == oldValue) return;

    KVUtil.putBool(isPolicyGranted, isAgree);
    _isPolicyGranted = isAgree;

    if (isAgree) {
      for (final task in _pendingTasks) {
        await task.onPolicyGrant();
      }
      _pendingTasks.clear();
    }
  }

  static bool isAgreePrivacyPolicy() {
    return _isPolicyGranted || KVUtil.getBool(isPolicyGranted, false);
  }
}

abstract class EnsurePolicyGrant {
  Future<void> onPolicyGrant();
}
