
package de.ivu.elect.jee.exchange;

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

import de.ivu.elect.jee.entity.tk.EntityFieldValue;
import de.ivu.elect.jee.faces.Messages;

public class UniqueConstraintViolation extends AbstractViolation {

  private static final long serialVersionUID = 1L;

  public static final String UNIQUE_TECHNICAL_KEY_CONSTRAINT = "validation.technical.key.constraint";

  private final String messageKey;

  private final List<EntityFieldValue> entityFieldValues = new ArrayList<>();

  public UniqueConstraintViolation(ViolationLevel violationLevel, List<EntityFieldValue> entityFieldValues) {
    this(violationLevel, UNIQUE_TECHNICAL_KEY_CONSTRAINT, entityFieldValues);
  }

  public UniqueConstraintViolation(ViolationLevel violationLevel, String messageKey, List<EntityFieldValue> entityFieldValues) {
    super(violationLevel);

    this.messageKey = messageKey;

    this.entityFieldValues.addAll(entityFieldValues);
  }

  @Override
  protected String createDefaultMessage() {
    return messageKey + entityFieldValues;
  }

  @Override
  public String getMessageKey() {
    return messageKey;
  }

  @Override
  public Object[] getMessageParameters(Messages messages) {
    return new Object[] {buildParameter(messages)};
  }

  private String buildParameter(Messages messages) {
    StringBuilder sb = new StringBuilder();

    for (EntityFieldValue entityFieldValue : entityFieldValues) {
      if (sb.length() > 0) {
        sb.append(", ");
      }

      sb.append(entityFieldValue.getMessage(messages));
    }

    return sb.toString();
  }
}
