package ub.scp2.managedBeans;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import ub.scp2.bo.RoleBo;
import ub.scp2.bo.SubjectBo;
import ub.scp2.entities.Role;

@FacesConverter(forClass=Role.class, value="roleConverter")
public class RoleConverter implements Converter {

	private RoleBo rolebo;
	
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent ui, String value) {
    	WebApplicationContext ctx =  FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        rolebo = ctx.getBean(RoleBo.class);
		if(value != ""){
			return rolebo.getRoleById(Integer.valueOf(value));
		}else{
			return null;
		}
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent ui, Object value) {
            if (value instanceof String){
                return (String)value;
            }
            
            Role r = (Role) value;
	    return ((Integer)r.getRoleId()) != null ? String.valueOf(r.getRoleId()) : null;

	}

}
