import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mListKlien.dart';
import 'package:absenkuv3/Repository/Service/koordinatorApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

abstract class KoordinatorListEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class getListKoordinatorListEvent extends KoordinatorListEvent {
  ModelFilter modelFilter;
  getListKoordinatorListEvent(BuildContext _context, this.modelFilter) {
    context = _context;
  }
}

class loadMoreEvent extends KoordinatorListEvent {
  late ScrollController scrollController;
  loadMoreEvent(BuildContext _context, GlobalKey<ScaffoldState> _scaffoldKey,
      ScrollController _scrollController) {
    context = _context;
    scaffoldKey = _scaffoldKey;
    scrollController = _scrollController;
  }
}

abstract class KoordinatorListState {
  List<Klien>? data;
  Klien? dataKlien;
}

class koordinatorListSuccessState extends KoordinatorListState {
  koordinatorListSuccessState(KoordinatorListEvent _event, List<Klien>? _data) {
    data = _data;
  }
}

class KoordinatorProgressState extends KoordinatorListState {}

class LoadMoreProgressState extends KoordinatorListState {
  LoadMoreProgressState(List<Klien>? _data) {
    data = _data;
  }
}

class KoordinatorErrorState extends KoordinatorListState {}

class KoordinatorListErrorState extends KoordinatorListState {}

class KoordinatorListBloc
    extends Bloc<KoordinatorListEvent, KoordinatorListState> {
  KoordinatorListState? initialState;
  List<Klien>? listKlien;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  KoordinatorListBloc(KoordinatorListState initialState) : super(initialState);

  @override
  Stream<KoordinatorListState> mapEventToState(
      KoordinatorListEvent event) async* {
    if (event is getListKoordinatorListEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield KoordinatorProgressState();
      Listklien dataKlien =
          await KoordinatorApi().getDataKlien(offset, modelFilter);
      if (dataKlien.success!) {
        listKlien = dataKlien.data;
        yield koordinatorListSuccessState(event, listKlien);
      } else
        yield KoordinatorErrorState();
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
              event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listKlien);
        Listklien dataKlien =
            await KoordinatorApi().getDataKlien(offset, modelFilter);
        if (dataKlien.success!) {
          listKlien!.addAll(dataKlien.data!);
        }
        yield koordinatorListSuccessState(event, listKlien);
      }
    }
  }
}
