import 'package:fis_common/event/event_type.dart';
import 'package:fis_lib_media_rt/base/channel.dart';
import 'package:fis_lib_media_rt/base/member.dart';
import 'package:fis_lib_media_rt/interface/channel.dart';
import 'package:fis_lib_media_rt/interface/member.dart';

import '../interface/player.dart';
import 'room.dart';

/// 播放器
abstract class BasePlayer implements IPlayer {
  final BaseRoom room;

  BasePlayer({required this.room}) {
    channelAdded = FEventHandler<BasePlayChannel>();
    channelRemoved = FEventHandler<BasePlayChannel>();
    _listenMembers();
  }

  @override
  late final FEventHandler<IPlayChannel> channelAdded;

  @override
  late final FEventHandler<IPlayChannel> channelRemoved;

  void _listenMembers() {
    final members = [room.localMember, ...room.remoteMembers];
    for (final member in members) {
      _listenMember(member);
    }
    room.memberJoined.addListener(_onMemberAdded);
    room.memberLeaved.addListener(_onMemberRemoved);
  }

  void _onMemberAdded(Object _, IMember e) {
    final member = e as BaseMember;
    _listenMember(member);
  }

  void _onMemberRemoved(Object _, IMember e) {
    final member = e as BaseMember;
    member.channelAdded.removeListener(_onMemberChannelAdded);
    member.channelRemoved.removeListener(_onMemberChannelRemoved);
  }

  void _onMemberChannelAdded(Object _, BaseChannel channel) {
    channelAdded.emit(this, channel as BasePlayChannel);
  }

  void _onMemberChannelRemoved(Object _, BaseChannel channel) {
    // channel.stop() //TODO:
    channelRemoved.emit(this, channel as BasePlayChannel);
  }

  void _listenMember(BaseMember member) {
    member.channelAdded.addListener(_onMemberChannelAdded);
    member.channelRemoved.addListener(_onMemberChannelRemoved);
  }
}
