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:flutter/foundation.dart';
import 'package:flutter/material.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 int mainViewWidth;
  late final int mainViewHeight;
  late final int subViewWidth;
  late final int subViewHeight;

  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 mainViewInfo = ntMember.memberInfo.deviceInfoList!.first;
      liveInfo = mainViewInfo;
      isDeviceMain = mainViewInfo.type == DeviceTypeEnum.desktop;
      // 是否存在摄像头画面，如果存在设置摄像头画面的宽高
      if (ntMember.memberInfo.deviceInfoList!.length > 1) {
        final subViewInfo = ntMember.memberInfo.deviceInfoList!.last;
        subViewWidth = subViewInfo.width;
        subViewHeight = subViewInfo.height;
        mainViewWidth = mainViewInfo.width;
        mainViewHeight = mainViewInfo.height;
      } else {
        subViewWidth = 0;
        subViewHeight = 0;
        mainViewWidth = mainViewInfo.width;
        mainViewHeight = mainViewInfo.height;
      }
    } 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();
      }
    }
  }
}
