package de.ivu.elect.business.email.entity;

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

import org.apache.commons.lang3.StringUtils;

import de.ivu.elect.business.datei.entity.Datei;
import de.ivu.elect.business.mandant.entity.EntityMitMandant;

public abstract class AbstractEmail implements EmailBase, EntityMitMandant {

  public static final String EMAIL_ADRESSE_SEPARATOR = ";";

  public static final String EMAIL_ADRESSE_SEPARATOR_REGEX = "[,;]";

  public static final String ANHANG_SEPARATOR = ", ";

  public boolean hasPersonendaten() {
    return getPersonendaten() != null;
  }

  public List<String> getEmpfaengerAdressen() {
    List<String> emailAdressen = new ArrayList<>();
    if (getEmpfaenger() !=null && StringUtils.isNotBlank(getEmpfaenger())) {
      String[] empfaengerArray = getEmpfaenger().split(EMAIL_ADRESSE_SEPARATOR_REGEX);
      for (String s : empfaengerArray) {
        if (StringUtils.isNotBlank(s.trim())) {
          emailAdressen.add(s.trim());
        }
      }
    }
    return emailAdressen;
  }

  public void setEmpfaengerAdressen(List<String> emailAdressen) {
    StringBuilder stringBuilder = new StringBuilder();
    boolean first = true;
    for (String emailAdresse : emailAdressen) {
      if (first) {
        first = false;
      } else {
        stringBuilder.append(EMAIL_ADRESSE_SEPARATOR);
      }
      stringBuilder.append(emailAdresse);
    }
    setEmpfaenger(stringBuilder.toString());
  }

  public boolean hasAnhaenge() {
    return !getDateis().isEmpty();
  }

  public String getAnhaengeAsString() {
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (Datei datei : getDateis()) {
      if (first) {
        first = false;
      } else {
        sb.append(ANHANG_SEPARATOR);
      }
      sb.append(datei.getOriginalDateiname());
    }
    return sb.toString();

  }

  @Override
  public EntityMitMandant getParent() {
    return getEmailVorgang();
  }
}
