import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/data/models/staff/bank_acc.dart';
import 'package:krow/features/profile/bank_account/data/bank_account_repository.dart';

part 'bank_account_event.dart';
part 'bank_account_state.dart';

class BankAccountBloc extends Bloc<BankAccountEvent, BankAccountState> {
  BankAccountBloc() : super(const BankAccountState()) {
    on<BankAccountEventInit>(_onInit);
    on<BankAccountEventUpdate>(_onSubmit);
  }

  FutureOr<void> _onInit(event, emit) async {
    await for (var account
        in getIt<BankAccountRepository>().getStaffBankAcc()) {
      emit(state.copyWith(bankAcc: account));
    }
  }

  FutureOr<void> _onSubmit(BankAccountEventUpdate event, emit) async {
    emit(state.copyWith(inLoading: true));
    var newBankAcc = BankAcc.fromJson(event.bankAcc);
    await getIt<BankAccountRepository>().putBankAcc(newBankAcc);
    emit(state.copyWith(success: true, bankAcc: newBankAcc));
  }
}
