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

abstract class AutoCompleteFilterPerusahaanEvent {}

class GetFilterPerusahaan extends AutoCompleteFilterPerusahaanEvent {
  String? keywords;
  GetFilterPerusahaan(this.keywords);
}

class GetFilterPerusahaanNoLoading extends AutoCompleteFilterPerusahaanEvent {
  String? keywords;
  GetFilterPerusahaanNoLoading(this.keywords);
}

class SetFilterPerusahaan extends AutoCompleteFilterPerusahaanEvent {
  DataDropdown? perusahaan;
  SetFilterPerusahaan(this.perusahaan);
}

abstract class AutoCompleteFilterPerusahaanState {
  List<DataDropdown>? listPerusahaan;
}

class GetFilterPerusahaanSuccess extends AutoCompleteFilterPerusahaanState {
  GetFilterPerusahaanSuccess(List<DataDropdown>? _listFilterPerusahaan) {
    listPerusahaan = _listFilterPerusahaan;
  }
}

class SetFilterPerusahaanSuccess extends AutoCompleteFilterPerusahaanState {
  DataDropdown? perusahaan;
  List<DataDropdown>? listPerusahaan;
  SetFilterPerusahaanSuccess(this.perusahaan, this.listPerusahaan);
}

class ErrorState extends AutoCompleteFilterPerusahaanState {}

class ProgressState extends AutoCompleteFilterPerusahaanState {}

class AutoCompleteFilterPerusahaanBloc
    extends Bloc<AutoCompleteFilterPerusahaanEvent, AutoCompleteFilterPerusahaanState> {
  List<DataDropdown>? listPerusahaan = <DataDropdown>[];

  AutoCompleteFilterPerusahaanBloc(AutoCompleteFilterPerusahaanState initialState)
      : super(initialState);

  @override
  Stream<AutoCompleteFilterPerusahaanState> mapEventToState(AutoCompleteFilterPerusahaanEvent event) async* {
    if (event is GetFilterPerusahaan) {
      yield ProgressState();
      listPerusahaan!.clear();
      DropdownRespon dropdownRespon = await DropdownApi().getFilterPerusahaan(event.keywords);
      if (dropdownRespon.success!) {
        listPerusahaan = dropdownRespon.data;
        yield GetFilterPerusahaanSuccess(listPerusahaan);
      } else {
        yield ErrorState();
      }
    } else if (event is SetFilterPerusahaan) {
      yield SetFilterPerusahaanSuccess(event.perusahaan, listPerusahaan);
    } else if (event is GetFilterPerusahaanNoLoading) {
      // yield ProgressState();
      listPerusahaan!.clear();
      DropdownRespon dropdownRespon = await DropdownApi().getFilterPerusahaan(event.keywords);
      if (dropdownRespon.success!) {
        listPerusahaan = dropdownRespon.data;
        yield GetFilterPerusahaanSuccess(listPerusahaan);
      } else {
        yield ErrorState();
      }
    }
  }
}
