import 'package:fis_common/index.dart';
import 'package:fis_lib_media_rt/base/channel.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/models.dart';
import 'package:fis_lib_media_rt/interface/capturer.dart';
import 'package:fis_lib_media_rt/interface/channel.dart';
import 'package:flutter/foundation.dart';

import '../capturer/index.dart';
import '../members.dart';

abstract class NTBasePublishChannel extends BasePublishChannel
    with NTChannelMixin {
  NTBasePublishChannel({required super.member});

  RtmpLiveInfo? liveInfo;
}

abstract class NTBasePlayChannel extends BasePlayChannel with NTChannelMixin {
  late final RtmpLiveInfo liveInfo;

  late final bool isDevice;
  late final bool isDeviceMain;

  NTBasePlayChannel({required super.member}) {
    final ntMember = member as NTRemoteMember;
    if (ntMember.isDevice) {
      isDevice = true;
      // 目前设备端主画面和摄像头分别用一个用户名加入房间，所以每个设备就是一个成员
      // Member与Channel是一对一
      final deviceLiveInfo = ntMember.memberInfo.deviceInfoList!.first;
      liveInfo = deviceLiveInfo;
      isDeviceMain = deviceLiveInfo.type == DeviceTypeEnum.desktop;
    } else {
      // 非设备
      isDevice = false;
      isDeviceMain = false;
      liveInfo = ntMember.memberInfo.liveInfo!;
    }
  }

  @protected
  void onSubViewIdChanged() {}

  void mountSubView(int subViewId) {}
}

mixin NTChannelMixin on BaseChannel {
  int _viewId = -1;
  NTCapturer? _capturer;

  int get viewId => _viewId;
  set viewId(int val) {
    if (_viewId != val) {
      _viewId = val;
      _handleViewIdUpdate();
    }
  }

  @override
  ICapturer createCapture() {
    _capturer ??= NTCapturer(channel: this);
    return _capturer!;
  }

  @protected
  void onViewIdChanged() {}

  void _handleViewIdUpdate() {
    onViewIdChanged();

    if (this is NTBasePlayChannel) {
      final playChannel = this as NTBasePlayChannel;
      if (playChannel.isDevice && !playChannel.isDeviceMain) {
        playChannel.onSubViewIdChanged();
      }
    }
  }
}
