import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/UserRepository.dart';
import 'package:road24_mobile/data/response/UserResponse.dart';
import 'package:road24_mobile/model/utils/Config.dart';

part 'user_event.dart';

part 'user_state.dart';

class UserBloc extends Bloc<UserEvent, UserState> {
  final UserRepository repository;

  UserBloc({required this.repository}) : super(UserInitial());

  @override
  Stream<UserState> mapEventToState(
    UserEvent event,
  ) async* {
    if (event is GetUserEvent) {
      try {
        yield UserInitial();
        final dynamic response = await repository.getUser();
        yield GetUserSuccessState(
          response: UserResponse.fromJson(response),
        );
      } catch (e) {
        yield UserLoadingError();
      }
    } else if (event is UpdateUserEvent) {
      try {
        yield UserInitial();
        await repository.updateUserFullData(
          firstName: event.firstName,
          lastName: event.lastName,
          birthday: event.birthday,
          email: event.email,
          gender: event.gender,
          language: Config.language,
        );
        yield UserUpdateSuccessState();
      } catch (e) {
        yield UserLoadingError();
      }
    }
    // else if (event is GetUserLocation) {
    //   try {
    //     yield UserInitial();

    //     var isLocationExist = MyApp.preferences?.getUserLocation() != null;

    //     if (!isLocationExist) {
    //       final dynamic response = await repository.getUser();

    //       var userData = UserResponse.fromJson(response);

    //       var locationInNetwork = userData.location;

    //       if (locationInNetwork == null) {
    //         yield NoLocationFound();
    //       } else {
    //         await MyApp.preferences?.setUserLocation(locationInNetwork);

    //         yield LocationFound();
    //       }
    //     } else {
    //       yield LocationFound();
    //     }
    //   } catch (e) {
    //     yield UserLoadingError();
    //   }
    // }
  }
}
