import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/exercise_device.dart';
import 'package:aitrainer_app/repository/customer_exercise_device_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 'customer_exercise_device_event.dart';
part 'customer_exercise_device_state.dart';

class CustomerExerciseDeviceBloc extends Bloc<CustomerExerciseDeviceEvent, CustomerExerciseDeviceState> {
  final CustomerExerciseDeviceRepository repository;
  final List<ExerciseDevice>? devices;

  CustomerExerciseDeviceBloc({required this.repository, required this.devices}) : super(CustomerExerciseDeviceInitial()) {
    _load();
    on<CustomerExerciseDeviceLoad>(_onLoad);
    on<CustomerExerciseDeviceAdd>(_onDeviceAdd);
    on<CustomerExerciseDeviceRemove>(_onDeviceRemove);
  }

  void _onLoad(CustomerExerciseDeviceLoad event, Emitter<CustomerExerciseDeviceState> emit) {
    emit(CustomerExerciseDeviceLoading());
    emit(CustomerExerciseDeviceReady());
  }

  void _onDeviceAdd(CustomerExerciseDeviceAdd event, Emitter<CustomerExerciseDeviceState> emit) async {
    emit(CustomerExerciseDeviceLoading());
    await repository.addDevice(event.device);
    Cache().initBadges();
    emit(CustomerExerciseDeviceReady());
  }

  void _onDeviceRemove(CustomerExerciseDeviceRemove event, Emitter<CustomerExerciseDeviceState> emit) async {
    emit(CustomerExerciseDeviceLoading());
    await repository.removeDevice(event.device);
    Cache().initBadges();
    emit(CustomerExerciseDeviceReady());
  }

  void _load() {
    if (repository.getDevices().isEmpty) {
      repository.setDevices(Cache().getCustomerDevices()!);
    }
    Track().track(TrackingEvent.exercise_device);
  }

  bool hasCustomerDevice(int exerciseDeviceId) {
    return repository.hasDevice(exerciseDeviceId);
  }
}
