/*
 * @Author: XianKaiQun
 * @Date: 2020-08-10 17:12:21
 * @LastEditors: XianKaiQun
 * @LastEditTime: 2020-09-18 16:25:08
 * @Description: 
 */

import 'package:wisdom_cli/wisdom_cli.dart';
import 'dart:math' as math;

/// 防作弊保存上传图片的概率
/// 储存Id，判断是否存在id
///
class AntiCheating {
  static AntiCheating? _instance;
  AntiCheating._();
  static AntiCheating? get instance {
    if (_instance == null) _instance = AntiCheating._();
    return _instance;
  }

  String _key = 'cheating_ids';
  List get _list => WisStorageUtil.get<List>(key: _key) ?? [];

  ///添加id
  _add(String? id) async {
    await WisStorageUtil.set(key: _key, data: [
      ..._list..remove(id), //去重
      id,
    ]);
  }

  ///上传防作弊图片的概率
  ///如果计算出来必须拍照，那就储存id，确保人员没有清除此id前所有操作都是必须上传图片的
  ///提交表单后调用[remove]
  Future<bool> probability(num probability, String? id) async {
    if (has(id)) {
      return true;
    }
    //百分百防作弊
    else if (probability >= 100) {
      await _add(id);
    }
    //百分之0防作弊
    else if (probability == 0) {
      await remove(id);
    }
    //算概率
    else {
      final random = math.Random().nextInt(100);
      if (random <= probability) {
        await _add(id);
      }
    }
    return has(id);
  }

  ///提交表单后，删除id
  ///
  remove(String? id) async {
    await WisStorageUtil.set(key: _key, data: [..._list..remove(id)]);
  }

  ///判断id是否存在
  bool has(String? id) {
    return _list.indexOf(id) != -1;
  }
}
