import 'dart:async';

import 'package:aitrainer_app/bloc/test_set_execute/test_set_execute_bloc.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise_type.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';

part 'test_set_new_event.dart';
part 'test_set_new_state.dart';

class TestSetNewBloc extends Bloc<TestSetNewEvent, TestSetNewState> {
  final ExerciseRepository exerciseRepository;
  final ExerciseType exerciseType;
  final int exercisePlanDetailId;
  final TestSetExecuteBloc executeBloc;

  late double quantity;
  late double unitQuantity;

  TestSetNewBloc(
      {required this.exerciseRepository, required this.exerciseType, required this.exercisePlanDetailId, required this.executeBloc})
      : super(TestSetNewInitial()) {
    exerciseRepository.exerciseType = exerciseType;
    quantity = 12;
    unitQuantity = 30;
    exerciseRepository.setQuantity(quantity);
    exerciseRepository.setUnit(exerciseType.unit);
    exerciseRepository.setUnitQuantity(unitQuantity);
    exerciseRepository.exercise!.exercisePlanDetailId = exercisePlanDetailId;
    exerciseRepository.start = DateTime.now();
    exerciseRepository.setCustomer(Cache().userLoggedIn!);
  }

  @override
  Stream<TestSetNewState> mapEventToState(
    TestSetNewEvent event,
  ) async* {
    try {
      if (event is TestSetNewChangeQuantity) {
        quantity = event.quantity;
        exerciseRepository.setQuantity(quantity);
      } else if (event is TestSetNewChangeQuantityUnit) {
        unitQuantity = event.quantity;
        exerciseRepository.setUnitQuantity(unitQuantity);
      } else if (event is TestSetNewSubmit) {
        yield TestSetNewLoading();
        exerciseRepository.end = DateTime.now();
        await exerciseRepository.addExercise();
        executeBloc.add(
            TestSetExecuteExerciseFinished(exerciseTypeId: exerciseType.exerciseTypeId, quantity: quantity, unitQuantity: unitQuantity));
        Track().track(TrackingEvent.test_set_new, eventValue: exerciseType.name);
      }
    } on Exception catch (e) {
      yield TestSetNewError(message: e.toString());
    }
  }
}
