import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/YandexRepository.dart';
import 'package:road24_mobile/data/response/GeoToAddress.dart';
part 'yandex_geo_code_event.dart';
part 'yandex_geo_code_state.dart';

class YandexGeoCodeBloc extends Bloc<YandexGeoCodeEvent, YandexGeoCodeState> {
  final YandexRepository repository;

  YandexGeoCodeBloc({required this.repository}) : super(YandexGeoCodeInitial());

  @override
  Stream<YandexGeoCodeState> mapEventToState(
    YandexGeoCodeEvent event,
  ) async* {
    if (event is YandexGeoCodeLatLngEvent) {
      try {
        yield YandexGeoCodeLatLngLoadingState();
        final response = await repository.getGEOUsingLatLang(
          lat: event.lat,
          long: event.long,
        );
        yield YandexGeoCodeLatLngSuccessState(
          response: GeoToAddressResponse.fromJson(response),
        );
      } catch (e) {
        print(e);
        yield YandexGeoCodeLatLngError(exception: e);
      }
    } else {
      yield YandexGeoCodeInitial();
    }

    if (event is YandexGeoCodeAddressEvent) {
      try {
        yield YandexGeoCodeInitial();
        await repository.getGEOUsingAddress(
          address: event.address,
        );
        yield YandexGeoCodeAddressSuccessState();
      } catch (e) {
        yield YandexGeoCodeLatLngError(exception: e);
      }
    }
  }
}
