package org.richfaces.realworld.session;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;
import org.jboss.seam.web.Session;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.fileupload.AvatarUpload;
import org.richfaces.realworld.fileupload.FileManager;
import org.richfaces.realworld.service.IUserAction;

@Name("authenticator")
public class Authenticator
{
    @Logger Log log;
    
    @In Identity identity;
    
    @In FacesMessages facesMessages;
    
    @In(create = true)
    IUserAction userAction;
    
    @In(create = true)
    FileManager fileManager;
    
    @In(create = true)
    AvatarUpload avatarUpload;
    
    /* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAuthenticator#authenticate()
	 */
    public boolean authenticate()
    {
        log.info("authenticating #0", identity.getUsername());
        try{
        if(userAction.login(identity.getUsername(), identity.getPassword())){
        	identity.addRole("admin");
        	if(!fileManager.isDirectoryPresent(identity.getUsername())){
        		fileManager.addDirectory(identity.getUsername());
        	}
        	return true;
        }
        }catch(Exception nre){
        	facesMessages.add("Invalid login or password");
        	return false;
        }
        return false; 
    }
    
    public String register(User user){
    	boolean errorHappened = false;
    	if(!user.getPassword().equals(user.getConfirmPassword())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent("register:confirmPassword");
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Confirm Password not equals password" , "Confirm Password not equals password"));
			errorHappened = true;
    	}
    	if(userAction.isUserExist(user.getLogin())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent("register:loginName");
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "User with this login already exist" , "User with this login already exist"));
			errorHappened = true;
    	}
    	if(errorHappened){
    		return "";
    	}
    	userAction.register(user);
    	if(avatarUpload.getAvatarItem() != null){
    		user.setAvatarPath(avatarUpload.getAvatarItem().getImage().getName());
    		fileManager.deleteDirectory(user.getLogin() + fileManager.getFileSeparator() + "avatars");
    		fileManager.addDirectory(user.getLogin() + fileManager.getFileSeparator() + "avatars");
    		try {
				fileManager.addImage(user.getLogin() + fileManager.getFileSeparator() + "avatars" + fileManager.getFileSeparator() + user.getAvatarPath(), avatarUpload.getAvatarItem().getData());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	return "main";
    }
    
    /**
	 * Logout from session. 
	 * 
	 * @return outcome which redirects to login page. 
	 */
	public void logout() {
		Session.instance().invalidate();
	}
}
