import 'dart:async';

import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';

import '../../../core/controller/im_controller.dart';
import '../../home/home_logic.dart';

class FriendRequestsLogic extends GetxController {
  final imLogic = Get.find<IMController>();
  final homeLogic = Get.find<HomeLogic>();
  final applicationList = <FriendApplicationInfo>[].obs;
  final loading = true.obs;
  final loadFailed = false.obs;
  late StreamSubscription faSub;

  @override
  void onInit() {
    faSub = imLogic.friendApplicationChangedSubject.listen((value) {
      _getFriendRequestsList();
    });
    super.onInit();
  }

  @override
  void onReady() {
    _getFriendRequestsList();
    super.onReady();
  }

  void retry() => _getFriendRequestsList();

  @override
  void onClose() {
    faSub.cancel();
    homeLogic.getUnhandledFriendApplicationCount();
    super.onClose();
  }

  void _getFriendRequestsList() async {
    loading.value = true;
    loadFailed.value = false;
    try {
      final list = await Future.wait([
        OpenIM.iMManager.friendshipManager
            .getFriendApplicationListAsRecipient(),
        OpenIM.iMManager.friendshipManager
            .getFriendApplicationListAsApplicant(),
      ]);

      final allList = <FriendApplicationInfo>[];
      allList
        ..addAll(list[0])
        ..addAll(list[1]);

      allList.sort((a, b) {
        if (a.createTime! > b.createTime!) {
          return -1;
        } else if (a.createTime! < b.createTime!) {
          return 1;
        }
        return 0;
      });

      var haveReadList = DataSp.getHaveReadUnHandleFriendApplication();
      haveReadList ??= <String>[];
      for (var e in list[0]) {
        var id = IMUtils.buildFriendApplicationID(e);
        if (!haveReadList.contains(id)) {
          haveReadList.add(id);
        }
      }
      DataSp.putHaveReadUnHandleFriendApplication(haveReadList);
      applicationList.assignAll(allList);
    } catch (e, s) {
      Logger.print('friend requests e: $e $s');
      loadFailed.value = true;
    } finally {
      loading.value = false;
    }
  }

  bool isISendRequest(FriendApplicationInfo info) =>
      info.fromUserID == OpenIM.iMManager.userID;

  void acceptFriendApplication(FriendApplicationInfo info) async {
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () => OpenIM.iMManager.friendshipManager
            .acceptFriendApplication(userID: info.fromUserID!),
      );
      IMViews.showToast(StrRes.addSuccessfully);
      _getFriendRequestsList();
    } catch (_) {
      IMViews.showToast(StrRes.addFailed);
    }
  }

  void refuseFriendApplication(FriendApplicationInfo info) async {
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () => OpenIM.iMManager.friendshipManager
            .refuseFriendApplication(userID: info.fromUserID!),
      );
      IMViews.showToast(StrRes.rejectSuccessfully);
      _getFriendRequestsList();
    } catch (_) {
      IMViews.showToast(StrRes.rejectFailed);
    }
  }
}
