import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/bean/request_friend_info.dart';
import 'package:location/data/repositories/friends_repository.dart';
import 'package:location/data/repositories/message_repository.dart';
import 'package:location/handler/error_handler.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/utils/toast_util.dart';

import '../../../dialog/common_confirm_dialog_impl.dart';
import '../../../utils/de_bounce.dart';

@injectable
class NewsPendingListController extends BaseController {
  final RxList<RequestFriendInfo> pendingList = RxList();

  final MessageRepository messageRepository;
  final FriendsRepository friendsRepository;

  final Debounce _saveDebounce = Debounce(debounceTime: 500);

  NewsPendingListController(this.messageRepository, this.friendsRepository);

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

  void back() {
    Get.back();
  }

  void refreshWaitingList() {
    messageRepository.getRequestFriendList().then((response) {
      final list = response.list;
      pendingList.clear();
      if (list != null) {
        pendingList.addAll(list);
      }
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onRefuseFriend(RequestFriendInfo item) {
    _saveDebounce
        .onClick(() => messageRepository.refuseFriendAccept(item.id).then((_) {
              ToastUtil.show(StringName.messageFriendRequestRejected);
              refreshWaitingList();
            }).catchError((error) {
              ErrorHandler.toastError(error);
            }));
  }

  onAgreeFriend(RequestFriendInfo item) {
    showAgreeAddFriendTipDialog(onConfirm: () {
      _saveDebounce.onClick(
          () => messageRepository.acceptFriendAccept(item.id).then((_) {
                ToastUtil.show(StringName.messageFriendRequestAgreed);
                refreshWaitingList();
              }).catchError((error) {
                ErrorHandler.toastError(error);
              }));
    });
  }
}
