import 'package:fis_lib_media_rt/implementations/trtc/capturer/index.dart';
import 'package:fis_lib_media_rt/implementations/trtc/member.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';

import '../channel.dart';
import '../client_getter_mixin.dart';

class TrtcRemoteMergedViewMain extends StatefulWidget {
  final TrtcPlayChannel channel;
  final bool isKeepCover;
  const TrtcRemoteMergedViewMain(this.channel,
      {this.isKeepCover = false, super.key});

  @override
  State<TrtcRemoteMergedViewMain> createState() =>
      _TrtcRemoteMergedViewMainState();
}

class _TrtcRemoteMergedViewMainState extends State<TrtcRemoteMergedViewMain>
    with TrtcClientGetterMixin {
  bool isPlaying = false;
  String _viewType = TRTCCloudDef.TRTC_VideoView_Texture;

  @override
  void initState() {
    widget.channel.playStateChanged.addListener(_onPlayingChanged);
    super.initState();
  }

  @override
  void dispose() {
    widget.channel.playStateChanged.removeListener(_onPlayingChanged);
    widget.channel.resetViewId();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      return _buildLive(
        constraints.maxWidth.toInt(),
        constraints.maxHeight.toInt(),
      );
    });
  }

  void _onPlayingChanged(Object _, bool e) {
    if (mounted) {
      setState(() {
        isPlaying = e;
      });
    }
  }

  Widget _buildLive(int width, int height) {
    final member = widget.channel.member as TrtcRemoteMember;
    final userId = member.userId!;
    return TRTCCloudVideoView(
      viewType: _viewType,
      textureParam: kIsWeb
          ? null
          : CustomRender(
              userId: userId,
              isLocal: false,
              streamType: TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
              width: width,
              height: height,
            ),
      onViewCreated: (viewId) async {
        widget.channel.viewId = viewId;

        /// 修改对齐方式
        WebTrtcUtil.setTRTCPlatformViewFitMode(
            viewId.toString(), widget.isKeepCover ? "cover" : "contain");
      },
      onTextureCreated: (textureId) {
        widget.channel.textureId = textureId;
        setState(() {
          _viewType = TRTCCloudDef.TRTC_VideoView_TextureView;
        });
      },
    );
  }
}
