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

abstract class AutoCompletePegawaiBawahanEvent {}

class GetPegawaiBawahan extends AutoCompletePegawaiBawahanEvent {
  String? keywords;
  String? idGroupM;
  GetPegawaiBawahan(this.keywords, this.idGroupM);
}

class GetPegawaiBawahanNoLoading extends AutoCompletePegawaiBawahanEvent {
  String? keywords;
  GetPegawaiBawahanNoLoading(this.keywords);
}

class SetPegawaiBawahan extends AutoCompletePegawaiBawahanEvent {
  DataDropdown? pegawaiBawahan;
  SetPegawaiBawahan(this.pegawaiBawahan);
}

abstract class AutoCompletePegawaiBawahanState {
  List<DataDropdown>? listPegawaiBawahan;
}

class GetPegawaiBawahanSuccess extends AutoCompletePegawaiBawahanState {
  GetPegawaiBawahanSuccess(List<DataDropdown>? _listPegawaiBawahan) {
    listPegawaiBawahan = _listPegawaiBawahan;
  }
}

class SetPegawaiBawahanSuccess extends AutoCompletePegawaiBawahanState {
  DataDropdown? pegawaiBawahan;
  List<DataDropdown>? listPegawaiBawahan;
  SetPegawaiBawahanSuccess(this.pegawaiBawahan, this.listPegawaiBawahan);
}

class ErrorState extends AutoCompletePegawaiBawahanState {}

class ProgressState extends AutoCompletePegawaiBawahanState {}

class AutoCompletePegawaiBawahanBloc extends Bloc<AutoCompletePegawaiBawahanEvent, AutoCompletePegawaiBawahanState> {
  List<DataDropdown>? listPegawaiBawahan = <DataDropdown>[];
  String? idGroupM = "";

  AutoCompletePegawaiBawahanBloc(AutoCompletePegawaiBawahanState initialState)
      : super(initialState);

  @override
  Stream<AutoCompletePegawaiBawahanState> mapEventToState(
      AutoCompletePegawaiBawahanEvent event) async* {
    if (event is GetPegawaiBawahan) {
      idGroupM = event.idGroupM;
      yield ProgressState();
      listPegawaiBawahan!.clear();
      DropdownRespon dropdownRespon = await DropdownApi().getPegawaiBawahan(event.keywords, idGroupM, 5);
      if (dropdownRespon.success!) {
        listPegawaiBawahan = dropdownRespon.data;
        yield GetPegawaiBawahanSuccess(listPegawaiBawahan);
      } else {
        yield ErrorState();
      }
    } else if (event is SetPegawaiBawahan) {
      yield SetPegawaiBawahanSuccess(event.pegawaiBawahan, listPegawaiBawahan);
    } else if (event is GetPegawaiBawahanNoLoading) {
      // yield ProgressState();
      listPegawaiBawahan!.clear();
      DropdownRespon dropdownRespon = await DropdownApi().getPegawaiBawahan(event.keywords, idGroupM, 5);
      if (dropdownRespon.success!) {
        listPegawaiBawahan = dropdownRespon.data;
        yield GetPegawaiBawahanSuccess(listPegawaiBawahan);
      } else {
        yield ErrorState();
      }
    }
  }
}
