import 'dart:async';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/util/track.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

part 'exercise_log_event.dart';

part 'exercise_log_state.dart';

class ExerciseLogBloc extends Bloc<ExerciseLogEvent, ExerciseLogState> {
  final ExerciseRepository exerciseRepository;
  @override
  ExerciseLogBloc({required this.exerciseRepository}) : super(ExerciseLogInitial());

  @override
  Stream<ExerciseLogState> mapEventToState(ExerciseLogEvent event) async* {
    try {
      if (event is ExerciseLogLoad) {
        yield ExerciseLogLoading();
        await Cache().setActivityDonePrefs(ActivityDone.isExerciseLogSeen);
        Track().track(TrackingEvent.exercise_log_open);
        yield ExerciseLogReady();
      } else if (event is ExerciseLogDelete) {
        yield ExerciseLogLoading();
        exerciseRepository.exerciseList!.remove(event.exercise);
        await exerciseRepository.deleteExercise(event.exercise);
        Track().track(TrackingEvent.exercise_log_delete);
        yield ExerciseLogReady();
      } else if (event is ExerciseResult) {
        yield ExerciseLogLoading();
        Track().track(TrackingEvent.exercise_log_result);
        yield ExerciseLogReady();
      }
    } on Exception catch (e) {
      yield ExerciseLogError(message: e.toString());
    }
  }
}
