import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/custom_model/Supply.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:meta/meta.dart';

part 'supply_event.dart';
part 'supply_state.dart';

class SupplyBloc extends Bloc<SupplyEvent, SupplyState> {
  final Repository repository;
  SupplyBloc({required this.repository}) : super(SupplyInitial());

  @override
  Stream<SupplyState> mapEventToState(
    SupplyEvent event,
  ) async* {
    if (event is DataFetched) {
      try {
        final response = await repository.getSupplies(event.type);
        var supplies = response.map((supply) {
          if (supply.id == event.selectedId) {
            supply.isSelected = true;
          }
          return supply;
        }).toList();
        yield SupplySuccess(items: supplies);
      } catch (_) {
        yield SupplyFailure();
      }
    } else if (event is OnRefresh) {
      try {
        final response = await repository.getSupplies(event.type);
        var supplies = response.map((supply) {
          if (supply.id == event.selectedId) {
            supply.isSelected = true;
          }
          return supply;
        }).toList();
        yield SupplySuccess(items: supplies);
      } catch (_) {
        yield SupplyFailure();
      }
    } else if (event is OnSearch) {
      try {
        final response = await repository.getSupplies(event.type, query: event.searchString ?? '');
        var supplies = response.map((supply) {
          if (supply.id == event.selectedId) {
            supply.isSelected = true;
          }
          return supply;
        }).toList();
        yield SupplySuccess(items: supplies);
      } catch (_) {
        yield SupplyFailure();
      }
    }
  }
}
