// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wyatt_authentication_bloc/src/domain/repositories/repositories.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';

part 'email_verification_state.dart';

class EmailVerificationCubit<Extra> extends Cubit<EmailVerificationState> {
  EmailVerificationCubit({
    required AuthenticationRepository<Extra> authenticationRepository,
  })  : _authenticationRepository = authenticationRepository,
        super(const EmailVerificationState());
  final AuthenticationRepository<Extra> _authenticationRepository;

  FutureOr<void> sendEmailVerification() async {
    emit(state.copyWith(status: FormStatus.submissionInProgress));
    final response = await _authenticationRepository.sendEmailVerification();
    emit(
      response.fold(
        (value) => state.copyWith(status: FormStatus.submissionSuccess),
        (error) => state.copyWith(
          errorMessage: error.message,
          status: FormStatus.submissionFailure,
        ),
      ),
    );
  }

  FutureOr<void> checkEmailVerification() async {
    emit(state.copyWith(status: FormStatus.submissionInProgress));

    final refresh = await _authenticationRepository.refresh();
    if (refresh.isErr) {
      final refreshError = refresh.err!;
      emit(
        EmailVerificationState(
          errorMessage: refreshError.message,
          status: FormStatus.submissionFailure,
        ),
      );
      return;
    }

    final currentAccount = await _authenticationRepository.getAccount();
    emit(
      currentAccount.fold(
        (value) => state.copyWith(
          isVerified: value.emailVerified,
          status: FormStatus.submissionSuccess,
        ),
        (error) => EmailVerificationState(
          errorMessage: error.message,
          status: FormStatus.submissionFailure,
        ),
      ),
    );
  }
}
