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:get/get.dart';
import 'package:image/image.dart';
import 'package:vid_player_demo/controller/player_controller.dart';
import 'package:vid_player_demo/widgets/image_cache.dart';

import 'widgets/canvas_player.dart';

class CanvasPlayerView extends StatefulWidget {
  const CanvasPlayerView(
    this.vidURL, {
    Key? key,
    this.viewSize = const Size(600, 500),
  }) : super(key: key);
  final String vidURL;
  final Size viewSize;

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

class _CanvasPlayerViewState extends State<CanvasPlayerView> {
  VidPlayerController? _playerController;
  VidPlayerController get playerController => _playerController!;
  VidDataHost? _vidDataHost;
  VidDataHost get dataHost => _vidDataHost!;
  bool _ifInit = false;
  double _brightness = 0;
  double _contrast = 0;
  double _matrixBrightness = 0.0;
  double _matrixContrast = 1.0;

  final colorFiltersMatrix = {
    "原色": <double>[
      1, 0, 0, 0, 0, // red
      0, 1, 0, 0, 0, // green
      0, 0, 1, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ],
    "红色通道": <double>[
      1, 0, 0, 0, 0, // red
      0, 0, 0, 0, 0, // green
      0, 0, 0, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ],
    "绿色通道": <double>[
      0, 0, 0, 0, 0, // red
      1, 0, 0, 0, 0, // green
      0, 0, 0, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ],
    "蓝色通道": <double>[
      0, 0, 0, 0, 0, // red
      0, 0, 0, 0, 0, // green
      1, 0, 0, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ],
    "低对比度": <double>[
      0.5, 0, 0, 0, 0, // red
      0, 0.5, 0, 0, 0, // green
      0, 0, 0.5, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ],
    "高对比度": <double>[
      2, 0, 0, 0, 0, // red
      0, 2, 0, 0, 0, // green
      0, 0, 2, 0, 0, // blue
      0, 0, 0, 1, 0, // alpha
    ]
  };

  /// 外部播放状态控制器
  PlayerStateController? _playerStateController;
  PlayerStateController get playerStateController => _playerStateController!;
  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(true);
          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();
  }

  void onClickPlay(Object sender, dynamic e) {
    print("${DateTime.now()} receive Play $e");
    clickPlay();
  }

  ///设置亮度传入的value范围为-100 ~ 100,brightness的范围为 -1 ~ 1
  void setBrightness(value) {
    final brightness = value / 100;
    if (brightness < -1 || brightness > 1) {
      return;
    }
    _matrixBrightness = brightness;
    final fliterMatrix = <double>[
      _matrixContrast, 0, 0, 0, _matrixBrightness, // red
      0, _matrixContrast, 0, 0, _matrixBrightness, // green
      0, 0, _matrixContrast, 0, _matrixBrightness, // blue
      0, 0, 0, 1, 0, // alpha
    ];
    playerController.setFilterMatrix(fliterMatrix);
  }

  ///设置对比度传入的value范围为value范围为-100 ~ 100,brightness的范围为 0 ~ 10
  void setContrast(value) {
    double contrast = 1;
    if (value < 0) {
      contrast = (value + 100) / 100;
    } else if (value >= 0) {
      contrast = value / 100 * 9 + 1;
    }
    if (contrast < 0 || contrast > 10) {
      return;
    }
    _matrixContrast = contrast;
    final fliterMatrix = <double>[
      _matrixContrast, 0, 0, 0, _matrixBrightness, // red
      0, _matrixContrast, 0, 0, _matrixBrightness, // green
      0, 0, _matrixContrast, 0, _matrixBrightness, // blue
      0, 0, 0, 1, 0, // alpha
    ];
    playerController.setFilterMatrix(fliterMatrix);
  }

  @override
  void initState() {
    super.initState();
    loadVidDataHost(widget.vidURL);
    _playerStateController = Get.find<PlayerStateController>();
    playerStateController.trigglePlay.addListener(onClickPlay);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SizedBox(
            width: widget.viewSize.width,
            height: widget.viewSize.height,
            child: RepaintBoundary(
              child: VidCanvasPlayer(
                _playerController as VidPlayerController,
              ),
            ),
          ),
          const Text('基于 Canvas 的播放器'),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                  onPressed: () {
                    clickPlay();
                  },
                  child: const Text('▶ Play')),
              ElevatedButton(
                  onPressed: () {
                    clickPause();
                  },
                  child: const Text('⏸ Pause')),
              ...colorFiltersMatrix.keys.map((key) {
                return ElevatedButton(
                  onPressed: () {
                    playerController.setFilterMatrix(colorFiltersMatrix[key]!);
                  },
                  child: Text(key),
                );
              }).toList(),
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(children: [
            const Text("明亮度"),
            SizedBox(
              width: 800,
              child: Slider(
                value: _brightness,
                max: 100,
                min: -100,
                divisions: 200,
                label: _brightness.round().toString(),
                onChanged: (double value) {
                  setBrightness(value);
                  setState(() {
                    _brightness = value;
                  });
                },
              ),
            )
          ]),
          Row(children: [
            const Text("对比度"),
            SizedBox(
              width: 800,
              child: Slider(
                value: _contrast,
                max: 100,
                min: -100,
                divisions: 200,
                label: _contrast.round().toString(),
                onChanged: (double value) {
                  setContrast(value);
                  setState(() {
                    _contrast = value;
                  });
                },
              ),
            )
          ])
        ],
      ),
    );
  }

  @override
  void dispose() {
    print("CanvasPlayerView dispose");
    playerController.dispose();
    dataHost.release();
    playerStateController.trigglePlay.removeListener(onClickPlay);
    super.dispose();
  }
}
