import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:meta/meta.dart';

part 'infinity_scroll_event.dart';
part 'infinity_scroll_state.dart';

class InfinityScrollBloc extends Bloc<InfinityScrollEvent, InfinityScrollState> {
  final Repository repository;
  InfinityScrollBloc({required this.repository}) : super(InfinityScrollInitial());
  static int pageSize = 20;

  @override
  Stream<InfinityScrollState> mapEventToState(
    InfinityScrollEvent event,
  ) async* {
    if (event is DataFetched && !(state is InfinityScrollSuccess && (state as InfinityScrollSuccess).hasReachedMax)) {
      try {
        if (state is InfinityScrollInitial) {
          final response = await repository.getInfinityList("url", page: 0, size: pageSize);
          yield InfinityScrollSuccess(items: response.results, page: 0, hasReachedMax: response.results.length < pageSize ? true : false);
        }
        if (state is InfinityScrollSuccess) {
          final currentState = state as InfinityScrollSuccess;
          var page = currentState.page + 1;
          final response = await repository.getInfinityList("url", page: page, size: pageSize);
          yield response.results.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : InfinityScrollSuccess(items: currentState.items + response.results, page: currentState.page + 1, hasReachedMax: false);
        }
      } catch (e) {
        var errorString = AppException.handleError(e);
        yield InfinityScrollFailure(errorString: errorString);
      }
    }
    if (event is OnRefresh) {
      try {
        final response = await repository.getInfinityList("url", page: 0, size: pageSize);
        yield InfinityScrollSuccess(items: response.results, page: 0, hasReachedMax: response.results.length < pageSize ? true : false);
      } catch (e) {
        yield InfinityScrollFailure(errorString: AppException.handleError(e));
      }
    }
  }
}
