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

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

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

abstract class BeritaState {
  List<DataBerita>? data;
  DataBerita? dataBerita;
}

class getListBeritaSuccessState extends BeritaState {
  getListBeritaSuccessState(BeritaEvent _event, List<DataBerita>? _data) {
    data = _data;
  }
}

class BeritaProgressState extends BeritaState {}

class LoadMoreProgressState extends BeritaState {
  LoadMoreProgressState(List<DataBerita>? _data) {
    data = _data;
  }
}

class BeritaErrorState extends BeritaState {}

class BeritaBloc extends Bloc<BeritaEvent, BeritaState> {
  BeritaState? initialState;
  List<DataBerita>? listBerita;
  ModelFilter? modelFilter;
  int offset = 0;
  int limit = ServerInfo.limit;

  BeritaBloc(BeritaState initialState) : super(initialState);

  @override
  Stream<BeritaState> mapEventToState(BeritaEvent event) async* {
    if (event is getListBeritaEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield BeritaProgressState();
      BeritaRespon beritaRespon =
          await BeritaApi().getDataBerita(offset, modelFilter);
      if (beritaRespon.success!) {
        listBerita = beritaRespon.data;
        yield getListBeritaSuccessState(event, listBerita);
      } else
        yield BeritaErrorState();
    } else if (event is loadMoreEvent) {
      if (event.scrollController.offset >=
              event.scrollController.position.maxScrollExtent &&
          !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listBerita);
        BeritaRespon beritaRespon =
            await BeritaApi().getDataBerita(offset, modelFilter);
        if (beritaRespon.success!) {
          listBerita!.addAll(beritaRespon.data!);
        }
        yield getListBeritaSuccessState(event, listBerita);
      }
    }
  }
}
