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

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

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

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

abstract class PengumumanState {
  List<DataPengumuman>? data;
  DataPengumuman? dataPengumuman;
}

class getListPengumumanSuccessState extends PengumumanState {
  getListPengumumanSuccessState(
      PengumumanEvent _event, List<DataPengumuman>? _data) {
    data = _data;
  }
}

class PengumumanProgressState extends PengumumanState {}

class LoadMoreProgressState extends PengumumanState {
  LoadMoreProgressState(List<DataPengumuman>? _data) {
    data = _data;
  }
}

class PengumumanErrorState extends PengumumanState {}

class PengumumanBloc extends Bloc<PengumumanEvent, PengumumanState> {
  PengumumanState? initialState;
  List<DataPengumuman>? listPengumuman;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  PengumumanBloc(PengumumanState initialState) : super(initialState);

  @override
  Stream<PengumumanState> mapEventToState(PengumumanEvent event) async* {
    if (event is getListPengumumanEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield PengumumanProgressState();
      PengumumanRespon pengumumanRespon =
          await PengumumanApi().getDataPengumuman(offset, modelFilter);
      if (pengumumanRespon.success!) {
        listPengumuman = pengumumanRespon.data;
        yield getListPengumumanSuccessState(event, listPengumuman);
      } else
        yield PengumumanErrorState();
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
              event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listPengumuman);
        PengumumanRespon pengumumanRespon =
            await PengumumanApi().getDataPengumuman(offset, modelFilter);
        if (pengumumanRespon.success!) {
          listPengumuman!.addAll(pengumumanRespon.data!);
        }
        yield getListPengumumanSuccessState(event, listPengumuman);
      }
    }
  }
}
