import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mIzin.dart';
import 'package:absenkuv3/Repository/Service/izinApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';

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

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

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

abstract class RekapIzinPegawaiState{
  List<DataIzin>? data;
  DataIzin? dataDetail;
}

class getListRekapIzinSuccessState extends RekapIzinPegawaiState{
  getListRekapIzinSuccessState(RekapIzinPegawaiEvent _event, List<DataIzin>? _data){
    data = _data;
  }
}

class parseDataRekapIzinState extends RekapIzinPegawaiState{
  parseDataRekapIzinState(DataIzin _dataDetail){
    dataDetail = _dataDetail;

  }
}

class RekapIzinProgressState extends RekapIzinPegawaiState{}

class LoadMoreProgressState extends RekapIzinPegawaiState{
  LoadMoreProgressState(List<DataIzin>? _data){
    data = _data;
  }
}

class RekapIzinErrorState extends RekapIzinPegawaiState{}

class RekapIzinPegawaiBloc extends Bloc<RekapIzinPegawaiEvent, RekapIzinPegawaiState>{
  ModelFilter? modelFilter;
  RekapIzinPegawaiState? initialState;
  List<DataIzin>? listIzin;
  int offset = 0;
  int limit = ServerInfo.limit;

  RekapIzinPegawaiBloc(RekapIzinPegawaiState initialState) : super(initialState);

  @override
  Stream<RekapIzinPegawaiState> mapEventToState(RekapIzinPegawaiEvent event) async*{
    if(event is getListRekapIzinEvent){
      offset = 0;
      modelFilter = event.modelFilter;
      yield RekapIzinProgressState();
      IzinRespon izinRespon = await IzinApi().getDataIzin(offset, 'rekapPegawai', modelFilter);
      if(izinRespon.success!){
        listIzin = izinRespon.data;
        yield getListRekapIzinSuccessState(event, listIzin);
      }
      else yield RekapIzinErrorState();
    }
    else if(event is loadMoreEvent){
      if (event.scrollController.offset >=
          event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listIzin);
        IzinRespon izinRespon = await IzinApi().getDataIzin(offset, 'rekapSaya', modelFilter);
        if(izinRespon.success!){
          listIzin!.addAll(izinRespon.data!);
        }
        yield getListRekapIzinSuccessState(event, listIzin);
      }
    }
  }
}