import 'package:chat/services/tim_service.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_friendship_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';

class TimBlockService extends GetxService {
  static TimBlockService get to => Get.find<TimBlockService>();

  /// 好友关系
  V2TIMFriendshipManager get friendshipManager =>
      TimService.to.instance.v2TIMFriendshipManager;

  @override
  void onInit() async {
    super.onInit();
    await fetchList();
  }

  /// 黑名单列表
  RxList<V2TimFriendInfo> blocks =
      List<V2TimFriendInfo>.empty(growable: true).obs;

  /// 拉取黑名单列表
  Future<void> fetchList() async {
    var blacklist = await friendshipManager.getBlackList();
    if (blacklist.code == 0) {
      blocks.value = blacklist.data!;
    }
  }

  /// 拉黑某人
  Future<bool> add(String userID) async {
    var result = await friendshipManager.addToBlackList(userIDList: [userID]);

    if (result.code == 0) {
      return result.data!.first.resultCode == 0;
    } else {
      UiTools.toast(result.desc);
      return false;
    }
  }

  /// 解除拉黑
  Future<bool> remove(String userID) async {
    var result =
        await friendshipManager.deleteFromBlackList(userIDList: [userID]);

    if (result.code == 0) {
      return result.data!.first.resultCode == 0;
    } else {
      UiTools.toast(result.desc);
      return false;
    }
  }
}
