import 'dart:collection';

import 'package:fis_lib_media_rt/base/channel.dart';
import 'package:fis_lib_media_rt/implementations/trtc/member.dart';
import 'package:fis_lib_media_rt/interface/channel.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';

import '../../base/player.dart';
import 'client_getter_mixin.dart';
import 'room.dart';

class TrtcPlayer extends BasePlayer with TrtcClientGetterMixin {
  TrtcPlayer({required TrtcRoom room}) : super(room: room) {
    room.events
        .on(TRTCCloudListener.onUserVideoAvailable, _onUserVideoAvailable);
    room.events
        .on(TRTCCloudListener.onUserAudioAvailable, _onUserAudioAvailable);
  }

  @override
  UnmodifiableListView<IPlayChannel> get channels => _combinChannels();

  UnmodifiableListView<BasePlayChannel> _combinChannels() {
    final arr = <BasePlayChannel>[];
    for (var member in room.remoteMembers) {
      arr.addAll(member.channels.map((e) => e as BasePlayChannel));
    }
    return UnmodifiableListView(arr);
  }

  void _onUserVideoAvailable(dynamic param) {
    final String userId = param['userId'];
    final bool available = param['available'];

    final member = _findMemberByUserId(userId);
    member?.handleVideoAvailableChange(available);
  }

  void _onUserAudioAvailable(dynamic param) {
    final String userId = param['userId'];
    final bool available = param['available'];

    final member = _findMemberByUserId(userId);
    member?.handleAudioAvailableChange(available);
  }

  TrtcRemoteMember? _findMemberByUserId(String userId) {
    final members = room.remoteMembers;
    final index = members.indexWhere((e) => e.userId == userId);
    if (index > -1) {
      return members[index] as TrtcRemoteMember;
    }
    return null;
  }
}
