import 'package:flutter/material.dart';

class VideoEstimatedTimeBar extends StatefulWidget {
  const VideoEstimatedTimeBar({super.key, required this.notifier});

  final EstimatedTimeNotifier notifier;

  @override
  State<VideoEstimatedTimeBar> createState() => _VideoEstimatedTimeBarState();
}

class _VideoEstimatedTimeBarState extends State<VideoEstimatedTimeBar> {
  EstimatedTimeNotifier get notifier => widget.notifier;

  String _position = '--:--';
  String _duration = '--:--';
  bool _hidden = true;

  @override
  void initState() {
    super.initState();
    notifier.addListener(_listener);
  }

  @override
  Widget build(BuildContext context) {
    return Offstage(
      offstage: _hidden,
      child: Align(
        alignment: Alignment.center,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            borderRadius: const BorderRadius.all(Radius.circular(6.0)),
          ),
          padding: const EdgeInsets.all(8.0),
          child: Text(
            '$_position / $_duration',
            style: const TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  void _listener() {
    if (notifier.duration.inHours == 0) {
      var strPosition = notifier.position.toString().split('.')[0];
      var strDuration = notifier.duration.toString().split('.')[0];
      _position = "${strPosition.split(':')[1]}:${strPosition.split(':')[2]}";
      _duration = "${strDuration.split(':')[1]}:${strDuration.split(':')[2]}";
    } else {
      _position = notifier.position.toString().split('.')[0];
      _duration = notifier.duration.toString().split('.')[0];
    }
    _hidden = notifier.isEnd;
    setState(() {});
  }

  @override
  void dispose() {
    notifier.removeListener(_listener);
    super.dispose();
  }
}

class EstimatedTimeNotifier with ChangeNotifier {
  Duration _position = const Duration(seconds: 0);
  Duration _duration = const Duration(seconds: 0);
  bool _isEnd = true;

  Duration get position => _position;

  Duration get duration => _duration;

  bool get isEnd => _isEnd;


  void update({required Duration position, required Duration duration}) {
    _position = position;
    _duration = duration;
    _isEnd = false;
    notifyListeners();
  }

  void dragEnd() {
    _isEnd = true;
    notifyListeners();
  }
}
