import 'package:absenkuv3/Repository/Model/mChekpoint.dart';
import 'package:absenkuv3/Repository/Service/patroliApi.dart';
import 'package:flutter/material.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';

abstract class PatroliEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}
class getListPatroliEvent extends PatroliEvent {
  ModelFilter? modelFilter;
  getListPatroliEvent(BuildContext? _context,this.modelFilter){
    context = _context;
  }
}
class loadMoreEvent extends PatroliEvent {
  late ScrollController scrollController;
  loadMoreEvent(BuildContext _context, GlobalKey<ScaffoldState> _scaffoldKey,
      ScrollController _scrollController) {
    context = _context;
    scaffoldKey = _scaffoldKey;
    scrollController = _scrollController;
  }
}
abstract class PatroliState{
  List<DataChekpoint>? data;
  DataChekpoint? dataChekpoint;
}
class getListPatroliSuccessState extends PatroliState {
  getListPatroliSuccessState(PatroliEvent _event,List<DataChekpoint>?_data){
    data = _data;
  }
}
class PatroliProgressState extends PatroliState{}
class LoadMoreProgressState extends PatroliState{
  LoadMoreProgressState(List<DataChekpoint>? _data){
    data = _data;
  }
}
class PatroliErrorState extends PatroliState{}

class PatroliBloc extends Bloc<PatroliEvent,PatroliState> {
  PatroliState? initialState;
  List<DataChekpoint>? listChekpoint;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  PatroliBloc(PatroliState initialState):super(initialState);
  @override
  Stream<PatroliState>mapEventToState(PatroliEvent event)async*{
    if (event is getListPatroliEvent) {
      offset =0;
      modelFilter = event.modelFilter;
      yield PatroliProgressState();
      CheckpointRespon checkpointRespon = await PatroliApi().getDataChekpoint(offset, modelFilter);
      if (checkpointRespon.success!) {
        listChekpoint = checkpointRespon.data;
        yield getListPatroliSuccessState(event,listChekpoint);
      }
      else yield PatroliErrorState();
    }
    else if(event is loadMoreEvent){
      if(event.scrollController.offset >= event.scrollController.position.maxScrollExtent &&
      !event.scrollController.position.outOfRange){
        offset = offset + limit;
        yield LoadMoreProgressState(listChekpoint);
        CheckpointRespon checkpointRespon = await PatroliApi().getDataChekpoint(offset, modelFilter);
        if (checkpointRespon.success!) {
          listChekpoint!.addAll(checkpointRespon.data!);
        }
        yield getListPatroliSuccessState(event, listChekpoint);
      }
    }
  }
}

