import 'package:flutter/cupertino.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_event.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_state.dart';
import 'package:hl_lieferservice/feature/authentication/service/userinfo.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/main.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_event.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  UserInfoService service;
  OperationBloc operationBloc;

  AuthBloc({required this.service, required this.operationBloc})
    : super(Unauthenticated()) {
    on<SetAuthenticatedEvent>(_auth);
    on<Logout>(_logout);
  }

  Future<void> _auth(
    SetAuthenticatedEvent event,
    Emitter<AuthState> emit,
  ) async {
    operationBloc.add(LoadOperation());
    await Future.delayed(Duration(seconds: 5));

    try {
      debugPrint("Retrieve user information");

      var response = await service.getUserinfo(event.sessionId);
      var state = Authenticated(sessionId: event.sessionId, user: response);
      locator.registerSingleton<Authenticated>(state);
      emit(state);
      operationBloc.add(FinishOperation());
    } catch (err, st) {
      debugPrint("Failed to retrieve user information");
      debugPrint(err.toString());
      debugPrint(st.toString());

      operationBloc.add(
        FailOperation(
          message: "Login war nicht erfolgreich. Probieren Sie es erneut.",
        ),
      );
    }
  }

  Future<void> _logout(Logout event, Emitter<AuthState> emit) async {
    emit(Unauthenticated());
  }
}
