import 'dart:async';

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()) {
    if (repository.getDevices().isEmpty) {
      repository.setDevices(Cache().getCustomerDevices()!);
    }
    Track().track(TrackingEvent.exercise_device);
  }

  @override
  Stream<CustomerExerciseDeviceState> mapEventToState(
    CustomerExerciseDeviceEvent event,
  ) async* {
    try {
      if (event is CustomerExerciseDeviceLoad) {
        yield CustomerExerciseDeviceLoading();
        yield CustomerExerciseDeviceReady();
      } else if (event is CustomerExerciseDeviceAdd) {
        yield CustomerExerciseDeviceLoading();
        await repository.addDevice(event.device);
        Cache().initBadges();
        yield CustomerExerciseDeviceReady();
      } else if (event is CustomerExerciseDeviceRemove) {
        yield CustomerExerciseDeviceLoading();
        await repository.removeDevice(event.device);
        Cache().initBadges();
        yield CustomerExerciseDeviceReady();
      }
    } on Exception catch (ex) {
      yield CustomerExerciseDeviceError(message: ex.toString());
    }
  }

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