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

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

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

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

abstract class PatroliPegawaiState{
  List<DataChekpoint>? data;
  DataChekpoint? dataChekpoint;
}

class getListPatroliSuccessState extends PatroliPegawaiState{
  getListPatroliSuccessState(PatroliPegawaiEvent _event, List<DataChekpoint>? _data){
    data = _data;
  }
}

class PatroliProgressState extends PatroliPegawaiState{}

class LoadMoreProgressState extends PatroliPegawaiState{
  LoadMoreProgressState(List<DataChekpoint>? _data){
    data = _data;
  }
}

class PatroliErrorState extends PatroliPegawaiState{}

class PatroliPegawaiBloc extends Bloc<PatroliPegawaiEvent, PatroliPegawaiState>{
  PatroliPegawaiState? initialState;
  List<DataChekpoint>? ListChekpoint;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  PatroliPegawaiBloc(PatroliPegawaiState initialState) : super(initialState);

  @override
  Stream<PatroliPegawaiState> mapEventToState(PatroliPegawaiEvent event) async*{
    if(event is getListPatroliEvent){
      offset = 0;
      modelFilter = event.modelFilter;
      yield PatroliProgressState();
      CheckpointRespon checkpointRespon = await PatroliApi().getDataChekpointPegawai(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().getDataChekpointPegawai(offset, modelFilter);
        if(checkpointRespon.success!){
          ListChekpoint!.addAll(checkpointRespon.data!);
        }
        yield getListPatroliSuccessState(event, ListChekpoint);
      }
    }
  }
}