
package de.ivu.elect.was.sitzberechnung.entity;

import java.util.function.Function;

import de.ivu.elect.jee.entity.Entity;
import de.ivu.elect.jee.entity.EntityPK;

public abstract class AbstractElectSitzberechnungEntity<E extends Entity> extends AbstractElectSitzberechnungObject {

  private final E entity;

  protected AbstractElectSitzberechnungEntity(E entity) {
    super(entity.getPk().toString());

    this.entity = entity;
  }

  public E getEntity() {
    return entity;
  }

  @Override
  public String toString() {
    return this.getClass().getSimpleName() + "{" + "entity = " + entity + "}";
  }

  public static <I extends Entity< ? , ? >> Function<I, String> mapEntityToKey() {
    return entity -> entity == null ? "" : mapPKToKey().apply((EntityPK< ? >) entity.getPk());
  }

  public static Function<EntityPK< ? >, String> mapPKToKey() {
    return entityPK -> entityPK == null ? "" : entityPK.toString();
  }

  public static <P extends EntityPK<Long>> P mapKeyToPK(Class<P> entityPKClass, String key) throws InstantiationException, IllegalAccessException {
    String entityPKClassName = entityPKClass.getSimpleName();
    if (key.startsWith(entityPKClassName)) {
      String id = key.replace(entityPKClassName + ":", "");
      P entityPK = entityPKClass.newInstance();
      entityPK.setId(Long.valueOf(id));
      return entityPK;
    }
    throw new RuntimeException("Key '" + key + "' passt nicht zu EntityPK-Klasse '" + entityPKClass.getName() + "'.");
  }
}
