import 'package:fis_measure/index.dart';
import 'package:fis_measure/interfaces/process/player/play_controller.dart';
import 'package:fis_vid/data_host/data_host.dart';
import 'package:flutter/material.dart';
import 'package:vid_player_demo/widgets/image_cache.dart';

import 'widgets/image_player.dart';

class ImagePlayerView extends StatefulWidget {
  const ImagePlayerView({Key? key}) : super(key: key);

  @override
  _ImagePlayerViewState createState() => _ImagePlayerViewState();
}

class _ImagePlayerViewState extends State<ImagePlayerView> {
  IPlayerController? _playerController;
  IPlayerController get playerController => _playerController!;
  VidDataHost? _vidDataHost;
  VidDataHost get dataHost => _vidDataHost!;
  bool _ifInit = false;
  List<String> mockData = [
    "http://cdn-bj.fis.plus/093BE20682B14BFB95D811F221A2B2FD.vid"
  ];

  void loadVidDataHost(String url) {
    print("${DateTime.now()} Load vid data host");
    _vidDataHost = VidDataHost(url);
    _playerController = VidPlayerController(dataHost: dataHost);
  }

  void clickPlay() {
    print("${DateTime.now()} Click play");
    if (_ifInit) {
      playerController.play();
    } else {
      dataHost.load().then((value) {
        if (value == null) {
          // TOOO: add log
        } else {
          playerController.setLoadState(value != null);
          Future.delayed(const Duration(milliseconds: 100), () {
            playerController.play();
          });
          print("${DateTime.now()} Load vid data host success");
        }
        _ifInit = true;
      });
    }
  }

  void clickPause() {
    print("${DateTime.now()} Click pause");
    playerController.pause();
  }

  @override
  void initState() {
    super.initState();
    loadVidDataHost(mockData[0]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('基于Image的播放器'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            const ShowImageCache(),
            ElevatedButton(
                onPressed: () {
                  clickPlay();
                },
                child: const Text('Play')),
            ElevatedButton(
                onPressed: () {
                  clickPause();
                },
                child: const Text('Pause')),
            SizedBox(
              width: 500,
              height: 500,
              child: RepaintBoundary(
                child: VidImagePlayer(
                  _playerController as VidPlayerController,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    print("ImagePlayerView dispose");
    playerController.dispose();
    dataHost.release();
    super.dispose();
  }
}
