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/AuthResponse.dart';
import 'package:road24_mobile/model/utils/Config.dart';

import '../../../my_app.dart';

part 'auth_event.dart';

part 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final UserRepository repository;

  AuthBloc({required this.repository}) : super(AuthInitial());

  @override
  Stream<AuthState> mapEventToState(
    AuthEvent event,
  ) async* {
    if (event is AddUserFullNameEvent) {
      try {
        yield AuthInitial();
        await repository.updateUserFullData(
          firstName: event.firstName,
          lastName: event.lastName,
          gender: '',
          email: '',
          language: Config.language,
        );
        yield AddUserFullNameSuccessState();
      } catch (e) {
        yield AuthLoadingError(exception: e);
      }
    }

    if (event is SMSSendingEvent) {
      try {
        yield AuthInitial();
        await repository.registerWithPhone(phoneNumber: event.phone);
        yield AuthSMSSentSuccessState();
      } catch (e) {
        yield AuthLoadingError(exception: e);
      }
    }

    if (event is SMSVerificationEvent) {
      try {
        yield AuthInitial();
        final response = await repository.verifySmsCode(
            phoneNumber: event.phone, smsCode: event.smsCode);
        await MyApp.preferences?.setToken(
          AuthResponse.fromJson(response).access,
        );
        await MyApp.preferences
            ?.setRefreshToken(AuthResponse.fromJson(response).refresh);
        yield SMSVerifiedSuccessState(AuthResponse.fromJson(response));
        print(response);
      } catch (e) {
        yield AuthLoadingError(exception: e);
      }
    }
  }
}
