import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/custom_model/LocationUnit.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:meta/meta.dart';

part 'location_event.dart';
part 'location_state.dart';

class LocationBloc extends Bloc<LocationEvent, LocationState> {
  final Repository repository;
  LocationBloc({required this.repository}) : super(LocationInitial());

  @override
  Stream<LocationState> mapEventToState(
    LocationEvent event,
  ) async* {
    if (event is DataFetched) {
      try {
        final response = await repository.getLocationUnits(
          locationType: event.locationType,
          filterId: event.filterId ?? -1,
        );
        var locations = response.map((location) {
          if (location.id == event.selectedId) {
            location.isSelected = true;
          }
          return location;
        }).toList();
        yield LocationSuccess(items: locations);
      } catch (_) {
        yield LocationFailure();
      }
    } else if (event is OnRefresh) {
      try {
        final response = await repository.getLocationUnits(
          locationType: event.locationType,
          filterId: event.filterId ?? -1,
        );
        var locations = response.map((location) {
          if (location.id == event.selectedId) {
            location.isSelected = true;
          }
          return location;
        }).toList();
        yield LocationSuccess(items: locations);
      } catch (_) {
        yield LocationFailure();
      }
    } else if (event is OnSearch) {
      try {
        final response = await repository.getLocationUnits(
          locationType: event.locationType,
          filterId: event.filterId ?? -1,
          query: event.searchString ?? '',
        );
        var locations = response.map((location) {
          if (location.id == event.selectedId) {
            location.isSelected = true;
          }
          return location;
        }).toList();
        yield LocationSuccess(items: locations);
      } catch (_) {
        yield LocationFailure();
      }
    }
  }
}
