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 RekapLemburPegawaiEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

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

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

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

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

class LemburProgressState extends RekapLemburPegawaiState {}

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

class LemburErrorState extends RekapLemburPegawaiState {}

class RekapLemburPegawaiBloc
    extends Bloc<RekapLemburPegawaiEvent, RekapLemburPegawaiState> {
  RekapLemburPegawaiState? initialState;
  List<DataLembur>? listLembur;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  RekapLemburPegawaiBloc(RekapLemburPegawaiState initialState)
      : super(initialState);

  @override
  Stream<RekapLemburPegawaiState> mapEventToState(
      RekapLemburPegawaiEvent event) async* {
    if (event is getListLemburEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield LemburProgressState();
      LemburRespon lemburRespon =
          await LemburApi().getDataRekapLemburPegawai(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().getDataRekapLemburPegawai(offset, modelFilter);
        if (lemburRespon.success!) {
          listLembur!.addAll(lemburRespon.data!);
        }
        yield getListLemburSuccessState(event, listLembur);
      }
    }
  }
}
