// 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:wyatt_authentication_bloc/src/core/constants/form_field.dart';
import 'package:wyatt_authentication_bloc/src/core/constants/form_name.dart';
import 'package:wyatt_authentication_bloc/src/domain/repositories/authentication_repository.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

part 'password_reset_state.dart';

class PasswordResetCubit<Extra> extends FormDataCubit<PasswordResetState> {
  PasswordResetCubit({
    required AuthenticationRepository<Extra> authenticationRepository,
  })  : _authenticationRepository = authenticationRepository,
        super(
          PasswordResetState(
            form: authenticationRepository.formRepository
                .accessForm(AuthFormName.passwordResetForm),
          ),
        );
  final AuthenticationRepository<Extra> _authenticationRepository;
  FormRepository get _formRepository =>
      _authenticationRepository.formRepository;

  @override
  String get formName => AuthFormName.passwordResetForm;

  void emailChanged(String value) {
    final Email email = Email.dirty(value);
    dataChanged(AuthFormField.email, email);
  }

  @override
  FutureOr<void> dataChanged<Value>(
    String key,
    FormInputValidator<Value, ValidationError> dirtyValue,
  ) {
    final form = _formRepository.accessForm(formName).clone();

    try {
      form.updateValidator(key, dirtyValue);
      _formRepository.updateForm(form);
    } catch (e) {
      rethrow;
    }

    emit(
      state.copyWith(form: form, status: form.validate()),
    );
  }

  @override
  FutureOr<void> reset() {
    final form = state.form.reset();
    _formRepository.updateForm(form);
    emit(
      state.copyWith(form: form, status: form.validate()),
    );
  }

  @override
  FutureOr<void> submit() async {
    if (!state.status.isValidated) {
      return;
    }

    emit(state.copyWith(status: FormStatus.submissionInProgress));

    final form = _formRepository.accessForm(formName);
    final email = form.valueOf<String?>(AuthFormField.email);

    if (email.isNullOrEmpty) {
      emit(
        state.copyWith(
          errorMessage: 'An error occured while retrieving data from the form.',
          status: FormStatus.submissionFailure,
        ),
      );
    }

    final response = await _authenticationRepository.sendPasswordResetEmail(
      email: email!,
    );

    emit(
      response.fold(
        (value) => state.copyWith(status: FormStatus.submissionSuccess),
        (error) => state.copyWith(
          errorMessage: error.message,
          status: FormStatus.submissionFailure,
        ),
      ),
    );
  }

  @override
  FutureOr<void> update(
    WyattForm form, {
    SetOperation operation = SetOperation.replace,
  }) {
    final WyattForm current = _formRepository.accessForm(formName).clone();
    final WyattForm newForm = operation.operation.call(current, form);
    _formRepository.updateForm(newForm);

    emit(
      state.copyWith(
        form: newForm,
        status: newForm.validate(),
      ),
    );
  }

  @override
  FutureOr<void> validate() {
    emit(
      state.copyWith(
        status: _formRepository.accessForm(formName).validate(),
      ),
    );
  }
}
