package isrp.viewbeans;

import isrp.hibernate.model.businessobject.Country;
import isrp.hibernate.model.businessobject.User;
import isrp.hibernate.model.util.Md5HashCode;
import isrp.model.service.CountryService;
import isrp.model.service.UserService;
import isrp.utils.IsrpUtils;
import isrp.utils.MessageUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.component.html.HtmlCommandButton;
import javax.faces.component.html.HtmlSelectBooleanCheckbox;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**Komponent wsparcia dla dodawania i edytowania użytkowników.
 *
 */
public class AddEditUserBean implements Serializable {	
	
	private static final long serialVersionUID = 1L;
	private VisitBean visitBean;
	private ArrayList<SelectItem> genderItemArray;	
	private ArrayList<SelectItem> countryItemArray;
	private UtilBean utilBean;
	private HtmlCommandButton downloadButton=null;
	private HtmlSelectBooleanCheckbox accepted=null;
	

	public AddEditUserBean(){
		genderItemArray = new ArrayList<SelectItem>();
		genderItemArray.add(new SelectItem(false, "Female"));
		genderItemArray.add(new SelectItem(true, "Male"));		
		
		countryItemArray = new ArrayList<SelectItem>();
		FacesContext ctx = FacesContext.getCurrentInstance();
		if (utilBean == null) utilBean=(UtilBean)ctx.getApplication().evaluateExpressionGet(ctx, "#{utilBean}", UtilBean.class);
		
		CountryService countrySer = utilBean.getServiceLocator().getCountryService();	
		List<Country> countries = countrySer.findAll();
		
		for (int i=0;i<countries.size();i++){
			countryItemArray.add(new SelectItem(countries.get(i).getId(),countries.get(i).getCountry() ));
		}
	}
	public void valueChangeListener(ValueChangeEvent valueChangeEvent)
	{	if (valueChangeEvent.getNewValue().equals(true) )	
		downloadButton.setDisabled(false);	
			else downloadButton.setDisabled(true);	
			//omija walidację
			FacesContext.getCurrentInstance().getRenderResponse();					
	}
	
	
	public String toEditUserPage(){
		visitBean.setCurrentUser(visitBean.getUser());
		return "edit_user_page";
	}
	
	public String editUser(){
		UserService userSer = utilBean.getServiceLocator().getUserService();
		userSer.update(visitBean.getCurrentUser());
		if (visitBean.getCurrentUser().getId() == visitBean.getUser().getId()){
			visitBean.setUser(visitBean.getCurrentUser());
			MessageUtil.addMessageToContext(FacesContext.getCurrentInstance(),"users.message.editSuccess");
			return "message_page";
		}
		//wymuszenie od¶wieżeenia listy użytkowników
		UsersListBean uBean = (UsersListBean) IsrpUtils.getBean(FacesContext.getCurrentInstance(), "sessionScope","usersListBean");
		uBean.setUsersList(null);
		return "users_list";
	}
	
	
	public String toAddNewUserPage(){
		visitBean.setCurrentUser(new User());		
		visitBean.getCurrentUser().setRole(new Byte("3"));
		return "add_user";
	}
	
	public String registerNewUser(){		
		//checking if email ....	
		FacesContext faces = FacesContext.getCurrentInstance();
		if (utilBean == null) utilBean=(UtilBean)faces.getApplication().evaluateExpressionGet(faces, "#{utilBean}", UtilBean.class);
		
		UserService userSer = utilBean.getServiceLocator().getUserService();
		
		if (userSer.checkIfEmailExistInDB(visitBean.getCurrentUser().getEmail())!=null){
			MessageUtil.addMessageToContext(faces, "registration.emailExists");
			return null;
		}
				
		User user = visitBean.getCurrentUser();
		String passwordCopy = user.getPassword();
		user.setPassword(Md5HashCode.getMd5HashCode(user.getPassword()));		
        user.setEntryDate(IsrpUtils.getCurrentDate());
        if (user.getRole()==null){
        	//autor
        	user.setRole(new Byte("2"));
        	userSer.registerNewAuthor(user,utilBean.getEmailConfiguration());        	
    		AuthenticationBean authenBean = new AuthenticationBean();
    		authenBean.setEmail(user.getEmail());
    		authenBean.setPassword(user.getPassword());
    		visitBean.setAuthenticationBean(authenBean);
    		visitBean.setCurrentPaper(null);
    		IsrpUtils.setBean(faces, "sessionScope", "authenticationBean", authenBean);    		    		                                   		
    		return "registration_success";
        }else{
        	//recenzent
        	//user.setRole(new Byte("3"));
        	userSer.registerNewReviewer(user,passwordCopy,utilBean.getEmailConfiguration());        	    	
        	return "users_list";
        }				
	}

	
	public HtmlCommandButton getDownloadButton() {
		return downloadButton;
	}
	public void setDownloadButton(HtmlCommandButton downloadButton) {
		this.downloadButton = downloadButton;
	}
	
	public HtmlSelectBooleanCheckbox getAccepted() {
		return accepted;
	}
	public void setAccepted(HtmlSelectBooleanCheckbox accepted) {
		this.accepted = accepted;
	}

	public ArrayList<SelectItem> getCountryItemArray() {
		return countryItemArray;
	}



	public void setCountryItemArray(ArrayList<SelectItem> countryItemArray) {
		this.countryItemArray = countryItemArray;
	}

	public VisitBean getVisitBean() {
		return visitBean;
	}


	public void setVisitBean(VisitBean visitBean) {
		this.visitBean = visitBean;
	}


	public ArrayList<SelectItem> getGenderItemArray() {
		return genderItemArray;
	}

	public void setGenderItemArray(ArrayList<SelectItem> genderItemArray) {
		this.genderItemArray = genderItemArray;
	}

	public void setUtilBean(UtilBean utilBean) {
		this.utilBean = utilBean;
	}

	public UtilBean getUtilBean() {
		return utilBean;
	}

}
