// timer_bloc.dart
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'timer_event.dart';
import 'timer_state.dart';

class TimerBloc extends Bloc<TimerEvent, TimerState> {
  Timer? _timer;

  TimerBloc() : super(const TimerInitial()) {
    on<StartTimer>(_onStartTimer);
    on<Tick>(_onTick);
  }

  void _onStartTimer(StartTimer event, Emitter<TimerState> emit) {
    const int duration = 300; // 5 minutes in seconds
    emit(const TimerRunInProgress(duration));
    _startTicker(duration);
  }

  void _onTick(Tick event, Emitter<TimerState> emit) {
    if (event.duration > 0) {
      emit(TimerRunInProgress(event.duration));
    } else {
      emit(const TimerRunComplete());
    }
  }

  void _startTicker(int duration) {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (duration - timer.tick > 0) {
        add(Tick(duration - timer.tick));
      } else {
        timer.cancel();
        add(const Tick(0));
      }
    });
  }

  @override
  Future<void> close() {
    _timer?.cancel();
    return super.close();
  }
}
