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.dart';
import 'package:aitrainer_app/model/exercise_plan_detail.dart';
import 'package:aitrainer_app/model/exercise_type.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'test_set_control_event.dart';
part 'test_set_control_state.dart';

class TestSetControlBloc extends Bloc<TestSetControlEvent, TestSetControlState> {
  final ExercisePlanDetail exercisePlanDetail;
  final TestSetExecuteBloc executeBloc;
  final ExerciseType exerciseType;
  final ExerciseRepository exerciseRepository = ExerciseRepository();

  late double initQuantity;
  late double initUnitQuantity;
  late double quantity;
  late double unitQuantity;
  late double oneRepMax;
  late int step;

  TestSetControlBloc({required this.exercisePlanDetail, required this.executeBloc, required this.exerciseType})
      : super(TestSetControlInitial()) {
    initBloc();
  }

  void initBloc() {
    oneRepMax = executeBloc.calculate1RM(exercisePlanDetail.exercises!.last.unitQuantity!, exercisePlanDetail.exercises!.last.quantity!);
    initQuantity = 12;
    quantity = initQuantity;
    initUnitQuantity = oneRepMax * 0.75;
    unitQuantity = initUnitQuantity;

    step = exercisePlanDetail.exercises!.length;
    exerciseRepository.customer = Cache().userLoggedIn;
    exerciseRepository.exerciseType = exerciseType;
  }

  @override
  Stream<TestSetControlState> mapEventToState(
    TestSetControlEvent event,
  ) async* {
    try {
      if (event is TestSetControlQuantityChange) {
        quantity = event.quantity;
      } else if (event is TestSetControlUnitQuantityChange) {
        unitQuantity = event.quantity;
      } else if (event is TestSetControlSubmit) {
        final Exercise exercise = Exercise();
        exercise.quantity = quantity;
        exercise.unit = exerciseType.unit;
        exercise.unitQuantity = unitQuantity;
        exercise.dateAdd = DateTime.now();
        exerciseRepository.exercise = exercise;

        await exerciseRepository.addExercise();
        executeBloc.add(
            TestSetExecuteExerciseFinished(exerciseTypeId: exerciseType.exerciseTypeId, quantity: quantity, unitQuantity: unitQuantity));
      }
    } on Exception catch (e) {
      yield TestSetControlError(message: e.toString());
    }
  }
}
