import 'dart:async';

import 'package:flutter/cupertino.dart';

import '../utils/common_util.dart';

class RelativeTimeText extends StatefulWidget {
  final int? timestamp;
  final Duration updateInterval;
  final TextStyle? style;

  final String? startPerchText;
  final String? endPerchText;

  const RelativeTimeText({
    super.key,
    required this.timestamp,
    this.updateInterval = const Duration(minutes: 1),
    this.style,
    this.startPerchText,
    this.endPerchText,
  });

  @override
  State<RelativeTimeText> createState() => _RelativeTimeTextState();
}

class _RelativeTimeTextState extends State<RelativeTimeText> {
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(widget.updateInterval, (_) => _updateTime());
  }

  void _updateTime() {
    if (mounted) {
      setState(() {});
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Text(
        '${widget.startPerchText ?? ''}${time2TimeDesc(widget.timestamp)}${widget.endPerchText ?? ''}',
        style: widget.style);
  }
}
