import 'dart:async';
import 'package:flutter/material.dart';
import './hours_minutes_seconds.dart';
import './num_tools.dart';

class AptSimpleTimerController {
  late Timer timer;
  late ShowAptSimpleTimerWithController controller;
}

class AptSimpleTimerWithController extends StatefulWidget {
  final int seconds;
  final Color timerColor;
  final double fontSize;
  final Function? onTimerEnd;
  final AptSimpleTimerController? controller;

  AptSimpleTimerWithController({
    required this.seconds,
    this.timerColor = Colors.black,
    this.fontSize = 14,
    this.onTimerEnd,
    this.controller,
  });

  @override
  State<StatefulWidget> createState() =>
      ShowAptSimpleTimerWithController(seconds, controller);
}

class ShowAptSimpleTimerWithController
    extends State<AptSimpleTimerWithController> {
  int seconds;
  late Timer timer;
  AptSimpleTimerController? controller;

  ShowAptSimpleTimerWithController(this.seconds, this.controller) {
    timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      if (seconds > 0) {
        setState(() {
          seconds--;
        });
      } else {
        if (widget.onTimerEnd != null) widget.onTimerEnd!();
      }
    });
    controller?.timer = timer;
    controller?.controller = this;
  }

  reBuild(int s) {
    seconds = s;
    timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      if (seconds > 0) {
        setState(() {
          seconds--;
        });
      } else {
        if (widget.onTimerEnd != null) {
          widget.onTimerEnd!();
        }
      }
    });
    controller?.timer = timer;
  }

  @override
  Widget build(BuildContext context) {
    var t = HoursMinutesSeconds(seconds);
    return Text(
      formatNum(
          '  ( ${(t.getDays() != 0) ? '  ${t.getMinutes() < 10 ? '0${t.getMinutes()}' : t.getMinutes()} '
              ': ${t.getSeconds() < 10 ? '0${t.getSeconds()}' : t.getSeconds()}' : ''
              '${t.getMinutes() < 10 ? '0${t.getMinutes()}' : t.getMinutes()} '
              ': ${t.getSeconds() < 10 ? '0${t.getSeconds()}' : t.getSeconds()}'} )',
          divide: false),
      textAlign: TextAlign.center,
      style: TextStyle(
        color: widget.timerColor,
        fontSize: widget.fontSize,
      ),
    );
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }
}
