import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import '../../../../data/api/app_exception.dart';
import '../../../../data/repository/repository.dart';

part 'stamp_event.dart';
part 'stamp_state.dart';

class StampBloc extends Bloc<StampEvent, StampState> {
  final Repository repository;
  int pageSize = 20;
  StampBloc(this.repository) : super(StampInitial());

  @override
  Stream<StampState> mapEventToState(
    StampEvent event,
  ) async* {
    if (event is DataFetched && !(state is StampSuccess && ((state as StampSuccess).hasReachedMax ?? false))) {
      try {
        if (state is StampInitial) {
          yield (StampLoading());
          final response = await repository.stamps(page: 0);
          yield StampSuccess(
            items: response,
            page: 0,
            hasReachedMax: response.length < pageSize ? true : false,
          );
        }
        if (state is StampSuccess) {
          final currentState = state as StampSuccess;
          int page = (currentState.page ?? 0) + 1;
          final response = await repository.stamps(page: page);
          yield response.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : StampSuccess(
                  items: (currentState.items ?? []) + response,
                  page: (currentState.page ?? 0) + 1,
                  hasReachedMax: false,
                );
        }
      } catch (e) {
        var errorString = AppException.handleError(e);
        yield (StampFailure(errorString: errorString));
      }
    }
    if (event is OnRefresh) {
      try {
        yield (StampLoading());
        final response = await repository.stamps(page: 0);
        yield StampSuccess(
          items: response,
          page: 0,
          hasReachedMax: response.length < pageSize ? true : false,
        );
      } catch (e) {
        yield (StampFailure(errorString: AppException.handleError(e)));
      }
    } else if (event is OnSearch) {
      try {
        yield (StampLoading());
        final response = await repository.stamps(page: 0);
        yield StampSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
      } catch (e) {
        yield (StampFailure(errorString: AppException.handleError(e)));
      }
    }
  }
}
