package ub.scp2.managedBeans;

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.SubjectBo;
import ub.scp2.entities.Role;
import ub.scp2.entities.Subject;

@FacesConverter(forClass=Subject.class, value="subjectConverter")
public class SubjectConverter implements Converter {
	
	private SubjectBo subjectbo;
	
	@Override
	public Object getAsObject(FacesContext arg0, UIComponent ui, String value) {
    	WebApplicationContext ctx =  FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        subjectbo = ctx.getBean(SubjectBo.class);
		if(value != ""){
			return subjectbo.getSubjectById(Long.valueOf(value));
		}else{
			return null;
		}
	}

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

	}

	public void setSubjectbo(SubjectBo subjectbo) {
		this.subjectbo = subjectbo;
	}
	
	
}
