import 'package:absenkuv3/Repository/Model/mAktivitas.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Service/aktivitasApi.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 AktivitasEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

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

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

abstract class AktivitasState {
  List<DataAktivitas>? data;
  DataAktivitas? dataAktivitas;
}

class getListAktivitasSuccessState extends AktivitasState {
  getListAktivitasSuccessState(
      AktivitasEvent _event, List<DataAktivitas>? _data) {
    data = _data;
  }
}

class AktivitasProgressState extends AktivitasState {}

class LoadMoreProgressState extends AktivitasState {
  LoadMoreProgressState(List<DataAktivitas>? _data) {
    data = _data;
  }
}

class AktivitasErrorState extends AktivitasState {}

class AktivitasBloc extends Bloc<AktivitasEvent, AktivitasState> {
  AktivitasState? initialState;
  List<DataAktivitas>? listAktivitas;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  AktivitasBloc(AktivitasState initialState) : super(initialState);

  @override
  Stream<AktivitasState> mapEventToState(AktivitasEvent event) async* {
    if (event is getListAktivitasEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield AktivitasProgressState();
      AktivitasRespon aktivitasRespon =
          await ActivitasApi().getDataAktivitas(offset, modelFilter);
      if (aktivitasRespon.success!) {
        listAktivitas = aktivitasRespon.data;
        yield getListAktivitasSuccessState(event, listAktivitas);
      } else
        yield AktivitasErrorState();
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
              event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listAktivitas);
        AktivitasRespon aktivitasRespon =
            await ActivitasApi().getDataAktivitas(offset, modelFilter);
        if (aktivitasRespon.success!) {
          listAktivitas!.addAll(aktivitasRespon.data!);
        }
        yield getListAktivitasSuccessState(event, listAktivitas);
      }
    }
  }
}
