import 'dart:collection';

import 'package:fis_lib_media_rt/base/channel.dart';
import 'package:fis_lib_media_rt/base/player.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/room.dart';
import 'package:fis_lib_media_rt/interface/channel.dart';

import 'members.dart';
import 'models.dart';
import 'rtc_adapter.dart';

class NTPlayer extends BasePlayer {
  late final NTRtmpRoom _rtmpRoom;
  NTPlayer({required super.room}) {
    _rtmpRoom = room as NTRtmpRoom;
    NTRtmp2RtcAdapter.adapter.mmberMuteVideoEvent.addListener(_onUserVideoMute);
    NTRtmp2RtcAdapter.adapter.mmberMuteAudioEvent.addListener(_onUserAudioMute);
  }

  @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 _onUserVideoMute(_, RtmpSetMuteEventArgs args) {
    final member = _findMemberByUserId(args.userId);
    member?.handleVideoAvailableChange(!args.isMute);
  }

  void _onUserAudioMute(_, RtmpSetMuteEventArgs args) {
    final member = _findMemberByUserId(args.userId);
    member?.handleAudioAvailableChange(!args.isMute);
  }

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