import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mShift2.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:absenkuv3/Repository/Service/shiftApi.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../CustomFunction.dart';

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

class GetListShiftKaryawanEvent extends ShiftKaryawanEvent{
  ModelFilter modelFilter;
  GetListShiftKaryawanEvent(BuildContext _context, this.modelFilter){
    context = _context;
  }
}

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

abstract class ShiftKaryawanState{
  List<DataShift>? data;
  DataShift? dataAktivitas;
}

class GetListShiftKaryawanSuccessState extends ShiftKaryawanState{
  GetListShiftKaryawanSuccessState(ShiftKaryawanEvent _event, List<DataShift>? _data){
    data = _data;
  }
}

class ShiftKaryawanProgressState extends ShiftKaryawanState{}

class LoadMoreProgressState extends ShiftKaryawanState{
  LoadMoreProgressState(List<DataShift>? _data){
    data = _data;
  }
}

class ShiftKaryawanErrorState extends ShiftKaryawanState{}

class ShiftKaryawanBloc extends Bloc<ShiftKaryawanEvent, ShiftKaryawanState>{
  ShiftKaryawanState? initialState;
  List<DataShift>? listShift;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  ShiftKaryawanBloc(ShiftKaryawanState initialState) : super(initialState);

  @override
  Stream<ShiftKaryawanState> mapEventToState(ShiftKaryawanEvent event) async*{
    // TODO: implement mapEventToState
    if(event is GetListShiftKaryawanEvent){
      offset = 0;
      modelFilter = event.modelFilter;
      yield ShiftKaryawanProgressState();
      ShiftRespon shiftRespon = await ShiftApi().getDataShiftKaryawan(offset, modelFilter);
      if(shiftRespon.success!){
        listShift = shiftRespon.data;
        yield GetListShiftKaryawanSuccessState(event, listShift);
      }
      else yield ShiftKaryawanErrorState();
    }
    else if(event is LoadMoreEvent){
      if (event.scrollController.offset >=
          event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listShift);
        ShiftRespon shiftRespon = await ShiftApi().getDataShiftKaryawan(offset, modelFilter);
        if(shiftRespon.success!){
          listShift!.addAll(shiftRespon.data!);
        }
        yield GetListShiftKaryawanSuccessState(event, listShift);
      }
    }
  }
}