package ru.micord.ervu.account_applications.service;

import exception.FormValidationException;
import model.BpmnVariableForSave;
import model.FieldData;

import ru.cg.webbpm.modules.core.error_handling.api.ErrorMetadata;
import ru.cg.webbpm.modules.core.error_handling.api.ErrorMetadataItem;
import ru.cg.webbpm.modules.core.runtime.api.LocalizedException;
import ru.cg.webbpm.modules.core.runtime.api.MessageBundleUtils;
import ru.cg.webbpm.modules.database.bean.entity_graph.EntityColumn;
import ru.cg.webbpm.modules.webkit.annotations.RpcSharedProperty;

import model.FormValidationResult;
import org.springframework.context.support.MessageSourceAccessor;
import service.FormValidator;
import service.container.AbstractGraphFormService;
import service.container.FormMode;
import service.container.FormService;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Обрезанный FormServiceImpl из платформы, отвязанный от BPMN зависимостей Поддержку BMPN решели из
 * этого проекта убрать
 *
 * @author Denis Ivanov
 */

public class UserAuthorityFormService extends AbstractGraphFormService implements FormService {
  private static final MessageSourceAccessor MESSAGE_SOURCE = MessageBundleUtils.createAccessor(
      "messages/form_messages");
  @RpcSharedProperty
  public FormMode mode = FormMode.SIMPLE; // this is to share property with the default Form.ts

  @Override
  public Object saveData(String s, List<FieldData> list, Boolean aBoolean,
      List<BpmnVariableForSave> list1) throws Exception {
    throw new UnsupportedOperationException("BPMN operations are unsupported");
  }

  protected Object saveDataById(Object selectedId, List<FieldData> fieldData) {
    Map<EntityColumn, Object> valuesForSave = this.getValuesForSave(selectedId, fieldData);
    if (valuesForSave.isEmpty()) {
      throw new LocalizedException("form_field.entity_not_exists", MESSAGE_SOURCE,
          new Object[] {selectedId}
      );
    }
    else {
      executeValidators(valuesForSave, fieldData);
      return this.save(fieldData, valuesForSave);
    }
  }

  protected void executeValidators(Map<EntityColumn, Object> valuesForSave,
      List<FieldData> fieldData) {
    if (this.formValidators != null && this.formValidators.length > 0) {
      StringBuilder errorMessageBuilder = new StringBuilder();
      ErrorMetadata errorMetadata = new ErrorMetadata();
      List<String> errorMessages = new LinkedList();

      for (FormValidator formValidator : this.formValidators) {
        FormValidationResult result = formValidator.validate(valuesForSave, fieldData);
        if (!result.isValid()) {
          String validationResultMessage = result.getMessage();
          errorMessages.add(validationResultMessage);
          errorMessageBuilder.append(String.join("\n", validationResultMessage));
          ErrorMetadataItem errorMetadataItem = new ErrorMetadataItem(result.getCode(),
              validationResultMessage
          );
          errorMetadata.getItems().add(errorMetadataItem);
        }
      }

      if (!errorMessages.isEmpty()) {
        throw new FormValidationException(errorMessageBuilder.toString(), errorMetadata,
            errorMessages
        );
      }
    }
  }


  @Override
  public List<FieldData> loadData() {
    throw new UnsupportedOperationException("Loading with no id is unsupported");
  }

  @Override
  public Object deleteData(String s, List<BpmnVariableForSave> list) {
    throw new UnsupportedOperationException("BPMN operations are unsupported");
  }

}
