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

abstract class AutoCompletePerusahaanEvent {}

class GetPerusahaan extends AutoCompletePerusahaanEvent {
  String? keywords;
  String? kategori;
  bool? loading;
  DataPerusahaan? selectedValue;
  GetPerusahaan(this.keywords, this.kategori,this.loading, this.selectedValue);
}

class SetPerusahaan extends AutoCompletePerusahaanEvent {
  DataPerusahaan? selectedValue;
  SetPerusahaan(this.selectedValue);
}

abstract class AutoCompletePerusahaanState {}

class GetPerusahaanSuccess extends AutoCompletePerusahaanState {
  PerusahaanRespon? dropdownRespon;
  DataPerusahaan? selectedValue;
  GetPerusahaanSuccess(this.dropdownRespon, this.selectedValue);
}

class SetPerusahaanSuccess extends AutoCompletePerusahaanState {
  PerusahaanRespon? dropdownRespon;
  DataPerusahaan? selectedValue;
  SetPerusahaanSuccess(this.dropdownRespon, this.selectedValue);
}

class ErrorState extends AutoCompletePerusahaanState {}

class ProgressState extends AutoCompletePerusahaanState {}

class AutoCompletePerusahaanBloc extends Bloc<AutoCompletePerusahaanEvent, AutoCompletePerusahaanState> {
  DataPerusahaan? selectedValue;
  PerusahaanRespon? dropdownRespon;

  AutoCompletePerusahaanBloc(AutoCompletePerusahaanState initialState) : super(initialState);

  @override
  Stream<AutoCompletePerusahaanState> mapEventToState(AutoCompletePerusahaanEvent event) async* {
    if (event is GetPerusahaan) {
      if(event.loading!) yield ProgressState();
      selectedValue = event.selectedValue;
      yield GetPerusahaanSuccess(null, selectedValue);
      // if (event.keywords != null && event.keywords != '') {
        dropdownRespon = await DropdownApi().getPerusahaan(event.keywords, event.kategori);
        if (dropdownRespon!.data != null) {
          yield GetPerusahaanSuccess(dropdownRespon!, selectedValue);
        } else if(dropdownRespon!.success! == false){
          yield GetPerusahaanSuccess(null, selectedValue);
        }
        else {
          yield ErrorState();
        }
      // }
    } else if (event is SetPerusahaan) {
        selectedValue = event.selectedValue;
        yield GetPerusahaanSuccess(dropdownRespon!, selectedValue!);
    }
  }
}
