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 ShiftTemanEvent{
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

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

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

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

class GetListShiftTemanSuccessState extends ShiftTemanState{
  GetListShiftTemanSuccessState(ShiftTemanEvent _event, List<DataShift>? _data){
    data = _data;
  }
}

class ShiftTemanProgressState extends ShiftTemanState{}

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

class ShiftTemanErrorState extends ShiftTemanState{}

class ShiftTemanBloc extends Bloc<ShiftTemanEvent, ShiftTemanState>{
  ShiftTemanState? initialState;
  List<DataShift>? listShift;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  ShiftTemanBloc(ShiftTemanState initialState) : super(initialState);

  @override
  Stream<ShiftTemanState> mapEventToState(ShiftTemanEvent event) async*{
    // TODO: implement mapEventToState
    if(event is GetListShiftTemanEvent){
      offset = 0;
      modelFilter = event.modelFilter;
      yield ShiftTemanProgressState();
      ShiftRespon shiftRespon = await ShiftApi().getDataShiftTeman(offset, modelFilter);
      if(shiftRespon.success!){
        listShift = shiftRespon.data;
        yield GetListShiftTemanSuccessState(event, listShift);
      }
      else yield ShiftTemanErrorState();
    }
    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().getDataShiftTeman(offset, modelFilter);
        if(shiftRespon.success!){
          listShift!.addAll(shiftRespon.data!);
        }
        yield GetListShiftTemanSuccessState(event, listShift);
      }
    }
  }
}