import 'dart:async';
import 'package:aitrainer_app/model/exercise_type.dart';
import 'package:aitrainer_app/model/workout_menu_tree.dart';
import 'package:aitrainer_app/repository/exercise_plan_repository.dart';
import 'package:aitrainer_app/repository/workout_tree_repository.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

part 'exercise_execute_plan_event.dart';

part 'exercise_execute_plan_state.dart';

class ExerciseExecutePlanBloc extends Bloc<ExerciseExecutePlanEvent, ExerciseExecutePlanState> {
  final WorkoutTreeRepository menuTreeRepository;
  final ExercisePlanRepository exercisePlanRepository = ExercisePlanRepository();
  int? customerId;
  int selectedNumber = 0;

  @override
  ExerciseExecutePlanBloc({required this.menuTreeRepository}) : super(ExerciseByPlanStateInitial());

  Future<void> getData() async {
    exercisePlanRepository.setCustomerId(customerId!);
    await exercisePlanRepository.getLastExercisePlan();
    await exercisePlanRepository.getExercisePlanDetails();
    menuTreeRepository.sortedTree.clear();
    menuTreeRepository.sortByMuscleType();

    menuTreeRepository.sortedTree.forEach((key, value) {
      List<WorkoutMenuTree> listWorkoutTree = value;
      listWorkoutTree.forEach((workoutTree) {
        workoutTree.selected = false;
        if (exercisePlanRepository.getExercisePlanDetailSize() > 0) {
          if (exercisePlanRepository.getExercisePlanDetailByExerciseId(workoutTree.exerciseTypeId) != null) {
            workoutTree.selected = true;
            this.selectedNumber++;
          }
        }
      });
    });
  }

  @override
  Stream<ExerciseExecutePlanState> mapEventToState(ExerciseExecutePlanEvent event) async* {
    try {
      if (event is ExerciseByPlanLoad) {
        yield ExerciseByPlanLoading();
        await this.getData();
        yield ExerciseByPlanReady();
      } else if (event is AddExerciseByPlanEvent) {
        yield ExerciseByPlanLoading();
        yield ExerciseByPlanReady();
      }
    } on Exception catch (e) {
      yield ExerciseByPlanError(message: e.toString());
    }
  }
}
