package utils;

import beans.MetodoFacadeLocal;
import entities.Metodo;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

@ManagedBean
@RequestScoped
public class MetodoConverter implements Converter {

    @EJB
    private MetodoFacadeLocal metodoFacade;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return metodoFacade.find(Integer.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s no es id de metodo valido", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof Metodo) {
            return String.valueOf(((Metodo) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s no es un metodo valido", modelValue)));
        }
    }

}