
package de.ivu.elect.jee.faces;

import java.util.Collection;

import javax.annotation.Nullable;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;

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

/**
 *  on 15.07.2015.
 */
public class EntityAusPerTkListeConverter<E extends Entity< ? , ? >> implements Converter {

  private final Collection<E> entities;

  public EntityAusPerTkListeConverter(Collection<E> entities) {
    this.entities = entities;
  }

  @Nullable
  @Override
  public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
    if (StringUtils.isBlank(s)) {
      return null;
    }
    for (E entity : entities) {
      if (entity.getTk().toString().equals(s)) {
        return entity;
      }
    }
    return null;
  }

  @Nullable
  @Override
  public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
    if (o == null) {
      return null;
    }

    return ((E) o).getTk().toString();
  }
}
