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 'plot_event.dart';
part 'plot_state.dart';

class PlotBloc extends Bloc<PlotEvent, PlotState> {
  final Repository repository;
  PlotBloc({required this.repository}) : super(PlotInitial());
  static int pageSize = 20;

  @override
  Stream<PlotState> mapEventToState(
    PlotEvent event,
  ) async* {
    if (event is DataFetched && !(state is PlotSuccess && (state as PlotSuccess).hasReachedMax)) {
      try {
        if (state is PlotInitial) {
          yield PlotLoading();
          final response = await repository.getPlots(page: 0, size: pageSize, searchString: "");
          yield PlotSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
        }
        if (state is PlotSuccess) {
          final currentState = state as PlotSuccess;
          var page = currentState.page + 1;
          final response = await repository.getPlots(page: page, size: pageSize, searchString: "");
          yield response.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : PlotSuccess(items: currentState.items + response, page: currentState.page + 1, hasReachedMax: false);
        }
      } catch (e) {
        var errorString = AppException.handleError(e);
        yield PlotFailure(errorString: errorString);
      }
    }
    if (event is OnRefresh) {
      try {
        yield PlotLoading();
        final response = await repository.getPlots(page: 0, size: pageSize, searchString: "");
        yield PlotSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
      } catch (e) {
        yield PlotFailure(errorString: AppException.handleError(e));
      }
    } else if (event is OnSearch) {
      try {
        yield PlotLoading();
        final response = await repository.getPlots(page: 0, size: pageSize, searchString: event.searchString);
        yield PlotSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
      } catch (e) {
        yield PlotFailure(errorString: AppException.handleError(e));
      }
    }
  }
}
