import 'package:fis_common/event/event_type.dart';
import 'package:fis_lib_media_rt/interface/channel.dart';
import 'package:fis_lib_media_rt/utils/id_generator.dart';
import 'package:flutter/foundation.dart';

import 'member.dart';

abstract class BasePublishChannel extends BaseChannel
    implements IPublishChannel {
  bool _isPreviewing = false;

  BasePublishChannel({required super.member}) {
    previewStateChanged = FEventHandler<bool>();
  }

  @override
  late final FEventHandler<bool> previewStateChanged;

  @override
  bool get isPreviewing => _isPreviewing;
  set isPreviewing(bool val) {
    if (val != _isPreviewing) {
      _isPreviewing = val;
      previewStateChanged.emit(this, val);
    }
  }
}

/// 播放频道(视频路)
abstract class BasePlayChannel extends BaseChannel implements IPlayChannel {
  bool _isPlaying = false;

  @override
  late final FEventHandler<bool> playStateChanged;

  @override
  late final FEventHandler<bool> videoMuteChanged;

  @override
  late final FEventHandler<bool> audioMuteChanged;

  BasePlayChannel({required super.member}) {
    playStateChanged = FEventHandler<bool>();
    videoMuteChanged = FEventHandler<bool>();
    audioMuteChanged = FEventHandler<bool>();
  }

  @override
  bool get isPlaying => _isPlaying;
  set isPlaying(bool val) {
    if (val != _isPlaying) {
      _isPlaying = val;
      playStateChanged.emit(this, val);
    }
  }

  @override
  @mustCallSuper
  void setAudioMute(bool isMute) {
    if (isMute != isMuteAudio) {
      super.setAudioMute(isMute);
      audioMuteChanged.emit(this, isMute);
    }
  }

  @override
  @mustCallSuper
  void setVideoMute(bool isMute) {
    if (isMute != isMuteVideo) {
      super.setVideoMute(isMute);
      videoMuteChanged.emit(this, isMute);
    }
  }

  @override
  @mustCallSuper
  Future<void> play() async {
    isPlaying = true;
  }

  @override
  @mustCallSuper
  Future<void> stop() async {
    isPlaying = false;
  }
}

abstract class BaseChannel implements IChannel {
  static final IDGenerator _idGenerator = IDGenerator();

  late final String _id;
  bool _isMuteAudio = false;
  bool _isMuteVideo = false;
  bool _isReady = false;

  /// 归属成员
  final BaseMember member;

  BaseChannel({
    required this.member,
  }) {
    _id = _idGenerator.generate();
    readyStateChanged = FEventHandler<bool>();
  }

  @override
  late final FEventHandler<bool> readyStateChanged;

  @override
  String get id => _id;

  @override
  bool get isMuteAudio => _isMuteAudio;

  @override
  bool get isMuteVideo => _isMuteVideo;

  @override
  bool get isReady => _isReady;

  @override
  @mustCallSuper
  void setAudioMute(bool isMute) {
    _isMuteAudio = isMute;
  }

  @override
  @mustCallSuper
  void setVideoMute(bool isMute) {
    _isMuteVideo = isMute;
  }

  @protected
  void updateReadyState(bool val) {
    _isReady = val;
    readyStateChanged.emit(this, val);
  }
}
