// 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/wyatt_authentication_bloc.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

part 'sign_in_state.dart';

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

  @override
  String get formName => AuthFormName.signInForm;

  void emailChanged(String value) {
    final emailValidatorType = _formRepository
        .accessForm(formName)
        .validatorOf(AuthFormField.email)
        .runtimeType;
    assert(
      emailValidatorType == Email,
      'Use emailCustomChanged(...) with validator $emailValidatorType',
    );

    final Email email = Email.dirty(value);
    dataChanged(AuthFormField.email, email);
  }

  void passwordChanged(String value) {
    final passwordValidatorType = _formRepository
        .accessForm(formName)
        .validatorOf(AuthFormField.password)
        .runtimeType;
    assert(
      passwordValidatorType == Password,
      'Use passwordCustomChanged(...) with validator $passwordValidatorType',
    );
    final Password password = Password.dirty(value);
    dataChanged(AuthFormField.password, password);
  }

  /// Same as [emailChanged] but with a custom [Validator].
  ///
  /// Sort of short hand for [dataChanged].
  void emailCustomChanged<
      Validator extends FormInputValidator<String?, ValidationError>>(
    Validator validator,
  ) {
    dataChanged(AuthFormField.email, validator);
  }

  /// Same as [passwordChanged] but with a custom [Validator].
  ///
  /// Sort of short hand for [dataChanged].
  void passwordCustomChanged<
      Validator extends FormInputValidator<String?, ValidationError>>(
    Validator validator,
  ) {
    dataChanged(AuthFormField.password, validator);
  }

  @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 {
    throw UnimplementedError('`submit()` is not implemented for SignInCubit, '
        'please use `signInWithEmailAndPassword()` or `signInAnonymously()`');
  }

  @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(),
      ),
    );
  }

  FutureOr<void> signInWithEmailAndPassword() async {
    if (state.status.isSubmissionInProgress) {
      return;
    }

    if (!state.status.isValidated) {
      return;
    }

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

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

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

    final uid = await _authenticationRepository.signInWithEmailAndPassword(
      email: email!,
      password: password!,
    );

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

  FutureOr<void> signInAnonymously() async {
    if (state.status.isSubmissionInProgress) {
      return;
    }

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

    final uid = await _authenticationRepository.signInAnonymously();

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

  FutureOr<void> signInWithGoogle() async {
    if (state.status.isSubmissionInProgress) {
      return;
    }
    // TODO(wyatt): maybe emit new state (to not carry an old errorMessage)
    emit(state.copyWith(status: FormStatus.submissionInProgress));

    final uid = await _authenticationRepository.signInWithGoogle();

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