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

import static java.util.Arrays.asList;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

import java.util.Collection;
import java.util.Locale;

import javax.annotation.Nullable;

import org.apache.commons.lang3.StringUtils;

import de.ivu.elect.business.person.entity.AbstractPersonendaten;

public abstract class AbstractStaat implements StaatBase {

  private static final long serialVersionUID = 1L;

  public static final String ATTRIBUTE_AS_LIST_SEPARATOR = AbstractPersonendaten.ATTRIBUTE_AS_LIST_SEPARATOR;

  public static final Locale DEUTSCHLAND_LOCALE = Locale.GERMANY;

  public static final String DEUTSCHLAND_CUSTOM_CODE = "000";

  private static final Collection<String> INLAND_CUSTOM_CODES = asList("0", "00", DEUTSCHLAND_CUSTOM_CODE);

  private static final Collection<String> INLAND_ISO_3166_ALPHA_2_CODES = asList(DEUTSCHLAND_LOCALE.getCountry());

  private static final Collection<String> INLAND_ALIASES = asList("deutschland", "deu", "de", "d", "brd", "ddr", "germany", "ger", "deutsch", "deutschl.");

  protected AbstractStaat() {
    super();
  }

  public boolean hasAnyCode() {
    return isNotBlank(getCustomCodeStaat()) || isNotBlank(getCustomCodeStaatsangehoerigkeit()) || isNotBlank(getIso3166Alpha2()) || isNotBlank(getIso3166Numerisch());
  }

  public boolean hasCustomCodeStaatsangehoerigkeit() {
    return isNotBlank(getCustomCodeStaatsangehoerigkeit());
  }

  public boolean hasCodes(Staat another) {
    return another != null && hasCodes(another.getIso3166Alpha2(), another.getCustomCodeStaat(), another.getCustomCodeStaatsangehoerigkeit());
  }

  public boolean hasCodes(@Nullable String iso3166Alpha2, @Nullable String customCodeStaat, @Nullable String customCodeStaatsangehoerigkeit) {
    return StringUtils.equals(getIso3166Alpha2(), iso3166Alpha2) && StringUtils.equals(getCustomCodeStaat(), customCodeStaat)
        && StringUtils.equals(getCustomCodeStaatsangehoerigkeit(), customCodeStaatsangehoerigkeit);
  }

  public boolean matchesInland() {
    return matchesInland((Staat) this);
  }

  public static boolean matchesInland(Staat staat) {
    return staat != null && (matchesInland(staat.getCustomCodeStaatsangehoerigkeit()) || matchesInland(staat.getCustomCodeStaat()) || matchesInland(staat.getIso3166Alpha2())
        || matchesInland(staat.getNameStaatsangehoerigkeit()) || matchesInland(staat.getNameStaat()));
  }

  public static boolean matchesInland(String value) {
    String valueNormalized = trimToEmpty(value).toLowerCase();

    return INLAND_CUSTOM_CODES.contains(valueNormalized) || INLAND_ISO_3166_ALPHA_2_CODES.contains(valueNormalized) || INLAND_ALIASES.contains(valueNormalized);
  }
}
