import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mLembur.dart';
import 'package:absenkuv3/Repository/Service/lemburApi.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 RekapLemburSayaEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class getListLemburEvent extends RekapLemburSayaEvent {
  ModelFilter? modelFilter;
  getListLemburEvent(BuildContext _context, this.modelFilter) {
    context = _context;
  }
}

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

abstract class RekapLemburSayaState {
  List<DataLembur>? data;
  DataLembur? dataLembur;
}

class getListLemburSuccessState extends RekapLemburSayaState {
  getListLemburSuccessState(
      RekapLemburSayaEvent _event, List<DataLembur>? _data) {
    data = _data;
  }
}

class LemburProgressState extends RekapLemburSayaState {}

class LoadMoreProgressState extends RekapLemburSayaState {
  LoadMoreProgressState(List<DataLembur>? _data) {
    data = _data;
  }
}

class LemburErrorState extends RekapLemburSayaState {}

class RekapLemburSayaBloc
    extends Bloc<RekapLemburSayaEvent, RekapLemburSayaState> {
  RekapLemburSayaState? initialState;
  List<DataLembur>? listLembur;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  RekapLemburSayaBloc(RekapLemburSayaState initialState) : super(initialState);

  @override
  Stream<RekapLemburSayaState> mapEventToState(
      RekapLemburSayaEvent event) async* {
    if (event is getListLemburEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield LemburProgressState();
      LemburRespon lemburRespon =
          await LemburApi().getDataRekapLemburSaya(offset, modelFilter);
      if (lemburRespon.success!) {
        listLembur = lemburRespon.data;
        yield getListLemburSuccessState(event, listLembur);
      } else
        yield LemburErrorState();
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
              event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listLembur);
        LemburRespon lemburRespon =
            await LemburApi().getDataRekapLemburSaya(offset, modelFilter);
        if (lemburRespon.success!) {
          listLembur!.addAll(lemburRespon.data!);
        }
        yield getListLemburSuccessState(event, listLembur);
      }
    }
  }
}
