import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Service/dropdownApi.dart';
import 'package:bloc/bloc.dart';

abstract class AutoCompletePegawaiEvent {}

class GetPegawai extends AutoCompletePegawaiEvent {
  String? keywords;
  ModelFilter? modelFilter;
  GetPegawai(this.keywords, this.modelFilter);
}

class SetPegawai extends AutoCompletePegawaiEvent {
  DataDropdown? pegawai;
  SetPegawai(this.pegawai);
}

abstract class AutoCompletePegawaiState {
  List<DataDropdown>? listPegawai;
}

class GetPegawaiSuccess extends AutoCompletePegawaiState {
  GetPegawaiSuccess(List<DataDropdown>? _listPegawai) {
    listPegawai = _listPegawai;
  }
}

class SetPegawaiSuccess extends AutoCompletePegawaiState {
  DataDropdown? pegawai;
  SetPegawaiSuccess(this.pegawai);
}

class ErrorState extends AutoCompletePegawaiState {}

class ProgressState extends AutoCompletePegawaiState {}

class AutoCompletePegawaiBloc
    extends Bloc<AutoCompletePegawaiEvent, AutoCompletePegawaiState> {
  List<DataDropdown>? listPegawai = <DataDropdown>[];

  AutoCompletePegawaiBloc(AutoCompletePegawaiState initialState)
      : super(initialState);

  @override
  Stream<AutoCompletePegawaiState> mapEventToState(
      AutoCompletePegawaiEvent event) async* {
    if (event is GetPegawai) {
      yield ProgressState();
      listPegawai!.clear();
      if (event.keywords != null && event.keywords != '') {
        DropdownRespon dropdownRespon =
            await DropdownApi().getPegawai(event.keywords, event.modelFilter);
        if (dropdownRespon.success!) {
          listPegawai = dropdownRespon.data;
          yield GetPegawaiSuccess(listPegawai);
        } else {
          yield ErrorState();
        }
      }
    } else if (event is SetPegawai) {
      yield SetPegawaiSuccess(event.pegawai);
    }
  }
}
