import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hub/features/local/index.dart';
import 'package:hub/features/storage/index.dart';

import 'index.dart';

class HomeBloc extends Bloc<HomeEvent, HomeState> {
  late StreamSubscription<bool> _completer;

  HomeBloc() : super(HomeState()) {
    on<HomeEvent>(_onHomeEvent);

    _completer = LocalsRepositoryImpl.license.stream.listen((v) {
      add(HomeEvent());
    });
  }

  @override
  Future<void> close() {
    _completer.cancel();
    return super.close();
  }

  Future<void> _onHomeEvent(HomeEvent event, Emitter<HomeState> emit) async {
    final devUUID =
        (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
    final userUUID =
        (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
    final cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    final userName =
        (await StorageHelper().get(ProfileStorageKey.userName.key)) ?? '';
    final userEmail =
        (await StorageHelper().get(SecureStorageKey.email.value)) ?? '';

    emit(state.copyWith(
      devUUID: devUUID,
      userUUID: userUUID,
      cliUUID: cliUUID,
      userName: userName,
      userEmail: userEmail,
    ));
  }
}
