// 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 'package:example_router/core/constants/form_field.dart';
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';

class EditProfileCubit extends FormDataCubitImpl {
  final AuthenticationRepository<int> authenticationRepository;

  EditProfileCubit(
    super._formRepository,
    super._formName, {
    required this.authenticationRepository,
  }) : super();

  @override
  Future<void> submit() async {
    emit(
      state.copyWith(
        status: FormStatus.submissionInProgress,
      ),
    );
    final user = (await authenticationRepository.getAccount()).ok;

    final form = state.form;
    final email = form.valueOf<String?>(AuthFormField.email);
    final oldPassword = form.valueOf<String?>(AppFormField.oldPassword);
    final newPassword = form.valueOf<String?>(AuthFormField.password);

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

    try {
      // await authenticationRepository.signInWithEmailAndPassword(
      //   email: user?.email ?? '',
      //   password: oldPassword ?? '',
      // );
      // await authenticationRepository.reauthenticateWithCredential();
      await authenticationRepository.updateEmail(email: email!);
      await authenticationRepository.updatePassword(password: newPassword!);
    } on Exception catch (e) {
      emit(
        state.copyWith(
          status: FormStatus.submissionFailure,
          errorMessage: e.toString(),
        ),
      );
    }
    emit(state.copyWith(status: FormStatus.submissionSuccess));
  }
}
