import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:provider/provider.dart';
import 'package:sport/provider/bluetooth.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/misc.dart';

const Color _color = Color(0xffFFC400);

class StepRealTimePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<StepRealTimePage> {
  static const String _startText = "00:00:00";
  ValueNotifier<int> _valueNotifierStep = ValueNotifier(0);
  ValueNotifier<String> _valueNotifier = ValueNotifier(_startText);
  ValueNotifier<bool> _valueNotifierPlay = ValueNotifier(true);

  Timer _timer;
  int _second;
  int _startStepValue;
  bool _paused;

  Function _function;

  Bluetooth _bluetooth;

  @override
  void initState() {
    super.initState();
    _bluetooth = Provider.of<Bluetooth>(context, listen: false);
    _bluetooth.stepRealTime(true);
    _function = () {
      var newStep = _bluetooth.stepRealtimeNotifier.value;
      if (_paused == true) {
        _startStepValue = newStep;
        return;
      }
      if (_startStepValue == null || _startStepValue == 0) {
        _startStepValue = newStep - 1;
      }
      _valueNotifierStep.value = _valueNotifierStep.value + (newStep - _startStepValue);
    };
    _bluetooth.stepRealtimeNotifier.addListener(_function);
  }

  @override
  void dispose() {
    _valueNotifierStep?.dispose();
    _valueNotifier?.dispose();
    _bluetooth?.stepRealtimeNotifier?.removeListener(_function);
    _bluetooth?.stepRealTime(false);
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  void _startStep() {
    print("1111111111 ${ Provider.of<Bluetooth>(context, listen: false).stepRealtimeSwitchNotifier}");
    if( Provider.of<Bluetooth>(context, listen: false).stepRealtimeSwitchNotifier.value == false) {
      ToastUtil.show("固件不支持");
      return;
    }
    if (_timer != null) {
      _timer.cancel();
      _valueNotifier.value = _startText;
      _second = -1;
      _timer = null;
      return;
    }

    _valueNotifier.value = " 00:00:00 ";
    _startTimer();
  }

  void _startTimer() {
    _second = 0;
    _playTimer();
  }

  void _stopTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
      return;
    }
  }

  void _playTimer() {
    _paused = false;
    _valueNotifierPlay.value = true;
    _timer?.cancel();
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      if (_second < 0) return;
      _second += 1;
      _valueNotifier.value =
          "${(_second ~/ 360).toString().padLeft(2, '0')}:${(_second ~/ 60).toString().padLeft(2, '0')}:${(_second % 60).toString().padLeft(2, '0')}";
    });
  }

  void _pauseTimer() {
    _paused = true;
    _valueNotifierPlay.value = false;
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: buildAppBar(context, title: "实时计步"),
        body: Column(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Center(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        ValueListenableBuilder(
                          valueListenable: _valueNotifierStep,
                          builder: (BuildContext context, value, Widget child) => Text(
                            "$value",
                            style: Theme.of(context).textTheme.headline1.copyWith(fontSize: 60.0),
                            strutStyle: fixedLine,
                          ),
                        ),
                        Text(
                          "步",
                          style: Theme.of(context).textTheme.subtitle2,
                        )
                      ],
                    ),
                    SizedBox(
                      height: 36.0,
                    ),
                    ValueListenableBuilder(
                      valueListenable: _valueNotifier,
                      builder: (_, value, __) => Text(
                        "$value",
                        style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 20.0),
                      ),
                    )
                  ],
                ),
              ),
            ),
            Flexible(
              flex: 1,
              child: ClipPath(
                clipper: _Path(),
                child: Container(
                  height: double.infinity,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    gradient:
                        new LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <Color>[Color(0xffFFD500), Color(0xffFFA200)]),
                  ),
                  child: Center(
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 80.0),
                      child: ValueListenableBuilder(
                                valueListenable: _valueNotifier,
                                builder: (_, value, __) => _timer == null
                                    ? InkWell(
                                        onTap: () => _startStep(),
                                        borderRadius: BorderRadius.all(Radius.circular(50.0)),
                                        child: Container(
                                            width: 215.0,
                                            height: 50.0,
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
                                              shape: BoxShape.rectangle,
                                              borderRadius: BorderRadius.all(Radius.circular(50.0)),
                                              // boxShadow: [BoxShadow(offset: Offset(0.0, 3), blurRadius: 3, spreadRadius: 0, color: Color(0x80f1f1f1))],
                                              gradient: LinearGradient(
                                                begin: Alignment.topCenter,
                                                end: Alignment.bottomCenter,
                                                colors: <Color>[Color(0xffFFFFFF), Color(0xffFFE6B2)],
                                              ),
                                            ),
                                            child: Text(
                                              "开始计步",
                                              style: TextStyle(color: const Color(0xffFFC400), fontSize: 16.0, fontWeight: FontWeight.w600),
                                              strutStyle: fixedLine,
                                            )),
                                      )
                                    : Center(
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: <Widget>[
                                            GestureDetector(
                                              child: Image.asset(
                                                "lib/assets/img/run_btn_over.png",
                                                width: 70.0,
                                                height: 70.0,
                                              ),
                                              onTap: () async {
                                                _stopTimer();
                                                var result = await showDialog(
                                                  context: context,
                                                  builder: (context) => CustomAlertDialog(
                                                      title: '是否保留数据？', textOk: '保留', textCancel: "不需要", ok: () => Navigator.of(context).pop(true)),
                                                );
                                                if (result == false) {
                                                  _valueNotifier.value = _startText;
                                                  _valueNotifierStep.value = 0;
                                                  _paused = true;
                                                  _startStepValue = 0;
                                                  Provider.of<Bluetooth>(context, listen: false).stepRealtimeNotifier.value = 0;
                                                }else{
                                                  setState(() {

                                                  });
                                                }
                                              },
                                            ),
                                            SizedBox(
                                              width: 60.0,
                                            ),
                                            ValueListenableBuilder(
                                              valueListenable: _valueNotifierPlay,
                                              builder: (_, val, __) => val
                                                  ? GestureDetector(
                                                      child: Image.asset(
                                                        "lib/assets/img/run_btn_suspend.png",
                                                        width: 70.0,
                                                        height: 70.0,
                                                      ),
                                                      onTap: () => _pauseTimer(),
                                                    )
                                                  : GestureDetector(
                                                      child: Image.asset(
                                                        "lib/assets/img/run_btn_play.png",
                                                        width: 70.0,
                                                        height: 70.0,
                                                      ),
                                                      onTap: () => _playTimer(),
                                                    ),
                                            ),
                                          ],
                                        ),
                                      ),
                              ),

                    ),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}

class _Path extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final rect = Rect.fromLTWH(-size.width / 2, 0, size.width * 2, size.height * 2);

    var path = Path();
    path.addArc(rect, 0, 45);
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return true;
  }
}
