// 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_form_bloc/src/core/enums/form_status.dart';
import 'package:wyatt_form_bloc/src/core/enums/set_operations.dart';
import 'package:wyatt_form_bloc/src/core/enums/validation_error.dart';
import 'package:wyatt_form_bloc/src/domain/form/wyatt_form.dart';
import 'package:wyatt_form_bloc/src/domain/input_validators/form_input_validator.dart';
import 'package:wyatt_form_bloc/src/domain/repositories/form_repository.dart';
import 'package:wyatt_form_bloc/src/presentation/features/form_data/form_data_cubit.dart';

part 'form_data_state_impl.dart';

abstract class FormDataCubitImpl extends FormDataCubit<FormDataStateImpl> {

  FormDataCubitImpl(this._formRepository, this._formName)
      : super(FormDataStateImpl(form: _formRepository.accessForm(_formName)));
  final FormRepository _formRepository;
  final String _formName;

  @override
  String get formName => _formName;

  @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> 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> reset() {
    final form = state.form.reset();
    _formRepository.updateForm(form);
    emit(
      state.copyWith(
        form: form,
        status: form.validate(),
      ),
    );
  }

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