
import 'package:intl/intl.dart';

import 'mmkv_util.dart';

typedef LimitedAction = void Function();

class DailyLimiterUtil {
  static Future<void> run({
    required String actionKey,
    required bool condition,
    required LimitedAction onExecute,
    int maxPerDay = 3,
  }) async {
    if (!condition) return;

    final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
    final dateKey = '${actionKey}_date';
    final countKey = '${actionKey}_count';

    final savedDate = KVUtil.getString(dateKey, '');
    int execCount = KVUtil.getInt(countKey, 0);

    if (savedDate != today) {
      execCount = 0;
      KVUtil.putString(dateKey, today);
      KVUtil.putInt(countKey, execCount);
    }

    if (execCount < maxPerDay) {
      onExecute();
      KVUtil.putInt(countKey, execCount + 1);
    }
  }

  static void printSavedData(String actionKey) {
    final dateKey = '${actionKey}_date';
    final countKey = '${actionKey}_count';
    final savedDate = KVUtil.getString(dateKey, '');
    final execCount = KVUtil.getInt(countKey, 0);

    print("保存的日期: $savedDate");
    print("保存的执行次数: $execCount");
  }

  // 清除指定 actionKey 的日期和执行次数数据
  static void clearDailyLimitData(String actionKey) {
    final dateKey = '${actionKey}_date';
    final countKey = '${actionKey}_count';

    KVUtil.putString(dateKey, null);
    KVUtil.putInt(countKey, 0);

    print("已清除 $actionKey 的日期和执行次数数据");
  }
}
