package ru.micord.ervu.account_applications.component.validator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import model.FieldData;
import model.FormValidationResult;
import model.SimpleFormValidationResult;
import org.springframework.context.support.MessageSourceAccessor;
import ru.micord.ervu.account_applications.component.model.RequiredField;
import service.FormValidatorWithCode;

import ru.cg.webbpm.modules.core.runtime.api.MessageBundleUtils;
import ru.cg.webbpm.modules.database.bean.entity_graph.EntityColumn;

public class RequiredFieldValidator extends FormValidatorWithCode {
  private static final MessageSourceAccessor MESSAGE_SOURCE = MessageBundleUtils.createAccessor(
      "messages/common_errors_messages");
  public RequiredField[] requiredFields;

  @Override
  public FormValidationResult validate(Map<EntityColumn, Object> values,
      List<FieldData> fieldData) {
    List<String> missingFields = new ArrayList<>();

    for (RequiredField requiredField : requiredFields) {
      if (isFieldNull(requiredField.name, values, fieldData)) {
        missingFields.add(requiredField.displayName);
      }
    }

    if (!missingFields.isEmpty()) {
      String message =
          MESSAGE_SOURCE.getMessage("form_field_required") + String.join(", ", missingFields);
      return SimpleFormValidationResult.invalid(code, message);
    }

    return SimpleFormValidationResult.valid(code);
  }

  private boolean isFieldNull(String fieldName, Map<EntityColumn, Object> values,
      List<FieldData> fieldData) {
    for (Map.Entry<EntityColumn, Object> entry : values.entrySet()) {
      if (fieldName.equals(entry.getKey().getName())) {
        return entry.getValue() == null;
      }
    }

    return true;
  }
}
