import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/features/profile/profile_main/domain/bloc/user_profile_event.dart';
import 'package:krow/features/profile/profile_main/domain/bloc/user_profile_state.dart';
import 'package:krow/features/profile/profile_main/domain/menu_tree.dart';
import 'package:krow/features/profile/profile_main/domain/profile_repository.dart';

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  final menuTree = MenuTree();

  ProfileBloc()
      : super(ProfileState(
          menu: MenuRoutItem(),
          roles: const [],
        )) {
    on<ProfileEventInit>(_onInit);
    on<ProfileEventSelectMenu>(_onSelectMenu);
    on<ProfileSwitchAvailability>(_onSwitchAvailability);
  }

  void _onInit(ProfileEventInit event, emit) async {
    var repo = getIt<ProfileRepository>();
    var menu = menuTree.buildMenuTree();
    emit(state.copyWith(
      menu: menu,
    ));

    emit(state.copyWith(
        roles: (await repo.getCachedProfileRoles())
            ?.map(mapRoleToRoleState)
            .toList()));

    await for (var staff in repo.getUserProfile()) {
      emit(state.copyWith(
        staff: staff,
      ));
    }

    emit(state.copyWith(
        roles: (await repo.getUserProfileRoles())
            .map(mapRoleToRoleState)
            .toList()));
  }

  RoleState mapRoleToRoleState(e) {
    return RoleState(
        name: e.skill!.name, experience: e.experience!, level: e.level!);
  }

  void _onSelectMenu(ProfileEventSelectMenu event, emit) {
    emit(state.copyWith(menu: event.item));
  }

  void _onSwitchAvailability(ProfileSwitchAvailability event, emit) {
    emit(state.copyWith(isAvailableNow: event.available));
  }
}
