import 'package:daniulive/controllers/interfaces/play_controller.dart';
import 'package:daniulive/controllers/merge_play_controller.dart';
import 'package:daniulive/views/merge_play_view/main_view.dart';
import 'package:daniulive/views/play_view.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/channel/channel.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/models.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/native_share.dart';
import 'package:fis_lib_media_rt/implementations/nt_rtmp/values.dart';
import 'package:flutter/material.dart';

class InnerView extends StatefulWidget {
  final NTPlayChannel channel;
  const InnerView({super.key, required this.channel});

  @override
  State<StatefulWidget> createState() => _InnerViewState();
}

class _InnerViewState extends State<InnerView> {
  bool _hasInit = false;
  bool _isMerge = false;

  late final IPlayController controller;

  @override
  void initState() {
    controller = _loadController();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      controller.init().then((_) {
        setState(() {
          _hasInit = true;
        });
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!_hasInit) {
      return const SizedBox();
    } else {
      if (_isMerge) {
        return MergePlayMainView(
          width: widget.channel.liveInfo.width,
          height: widget.channel.liveInfo.height,
          controller: controller as MergePlayController,
        );
      } else {
        return PlayView(controller: controller);
      }
    }
  }

  IPlayController _loadController() {
    if (widget.channel.isDeviceMain) {
      _isMerge = (widget.channel.liveInfo as DeviceRtmpLiveInfo).isMerge;
      if (_isMerge) {
        return NTNativeShare.playControllers.get(MERGE_DEVICE_NATIVE_SIGN)!;
      }
    }
    return NTNativeShare.playControllers.get(widget.channel.member.userId!)!;
  }
}
