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 '../capturer/index.dart';
import '../channel.dart';
import '../client_getter_mixin.dart';

class TrtcRemoteDeviceView extends StatefulWidget {
  final TrtcPlayChannel channel;
  const TrtcRemoteDeviceView(this.channel, {super.key});

  @override
  State<TrtcRemoteDeviceView> createState() => _TrtcRemoteDeviceViewState();
}

class _TrtcRemoteDeviceViewState extends State<TrtcRemoteDeviceView>
    with TrtcClientGetterMixin {
  bool isPlaying = false;

  @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: TRTCCloudDef.TRTC_VideoView_TextureView,
      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.setRemoteViewToFit(viewId.toString());
      },
    );
  }
}
