import 'package:absenkuv3/Repository/Model/MonitorAbsen/mMonitorAbsen.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mLembur.dart';
import 'package:absenkuv3/Repository/Service/MonitorAbsensi/monitorAbsenApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

abstract class MonitorListLemburEvent {
  BuildContext? context;
}

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

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

class loadMoreEvent extends MonitorListLemburEvent {
  late ScrollController scrollController;
  loadMoreEvent(ScrollController _scrollController) {
    scrollController = _scrollController;
  }
}

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

class SuccessMonitorListLemburMonitorState extends MonitorListLemburMonitorState {
  SuccessMonitorListLemburMonitorState(List<DataLembur>? _data) {
    data = _data;
  }
}

class ProgressMonitorListLemburMonitorState extends MonitorListLemburMonitorState {}

class ErrorMonitorIzinState extends MonitorListLemburMonitorState {}

class MonitorListLemburBloc extends Bloc<MonitorListLemburEvent, MonitorListLemburMonitorState> {
  MonitorListLemburBloc(MonitorListLemburMonitorState initialState) : super(initialState);
  List<DataLembur>? listLembur;
  int offset = 0;
  int limit = ServerInfo.limit;
  ModelFilter? modelFilter;
  @override
  Stream<MonitorListLemburMonitorState> mapEventToState(MonitorListLemburEvent event) async* {
    if (event is GetMonitorListLemburEvent) {
      offset = 0;
      debugPrint(offset.toString());
      modelFilter = event.modelFilter;
      yield ProgressMonitorListLemburMonitorState();
      LemburRespon data = await MonitorAbsenApi()
          .getDataLemburMonitor(offset, modelFilter);
      if (data.success!) {
        listLembur = data.data;
        yield SuccessMonitorListLemburMonitorState(listLembur);
      } else {
        yield ErrorMonitorIzinState();
      }
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
          event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listLembur);
        LemburRespon data = await MonitorAbsenApi()
            .getDataLemburMonitor(offset, modelFilter);
        if (data.success!) {
          listLembur!.addAll(data.data!);
        }
        yield SuccessMonitorListLemburMonitorState(listLembur);
      }
    }
  }
}
