import 'package:chewie/chewie.dart';
import 'package:flutter/Material.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/resource/assets.gen.dart';
import 'package:video_player/video_player.dart';

import '../../../../widget/video/custom_material_controls.dart';

/// 键盘教程页-视频引导页-Android平台-Controller
@injectable
class KeyboardTutorialVideoAndroidViewController extends BaseController {
  /// 视频是否初始化
  final Rx<bool> isVideoInitialized = false.obs;

  /// 视频是否正在播放
  final Rx<bool> isVideoPlaying = false.obs;

  /// 视频控制器
  late VideoPlayerController videoController;

  /// 新增 Chewie 控制器
  late ChewieController chewieController;

  @override
  void onInit() {
    super.onInit();
    _initVideoController();
  }

  @override
  void onClose() {
    // 移除视频状态监听器
    chewieController.removeListener(_syncPlayStatus);
    // 释放资源
    chewieController.dispose();
    videoController.dispose();
    super.onClose();
  }

  /// 初始化视频播放器
  void _initVideoController() {
    videoController = VideoPlayerController.asset(
        Assets.videos.keyboardTutorialVideo,
      )
      ..initialize().then((_) {
        isVideoInitialized.value = true;
        // 初始化 Chewie 控制器
        chewieController = ChewieController(
          videoPlayerController: videoController,
          // 自动开始播放
          autoPlay: true,
          // 设置循环播放
          looping: true,
          // 是否显示右上角的选项按钮
          showOptions: false,
          // 速度选项
          playbackSpeeds: [0.5, 1.0, 1.5, 2.0],
          // 自定义UI
          customControls: CustomMaterialControls(),
        );
        chewieController.addListener(_syncPlayStatus);
      });

    videoController.setLooping(true);
  }

  /// 更新视频的播放状态
  void _syncPlayStatus() {
    final isPlaying = chewieController.videoPlayerController.value.isPlaying;
    if (isVideoPlaying.value != isPlaying) {
      isVideoPlaying.value = isPlaying;
    }
  }

  /// 返回
  void clickBack() {
    Get.back();
  }

  /// 播放
  void clickPlay() {
    videoController.play();
  }

  /// 暂停
  void clickPause() {
    videoController.pause();
  }
}
