package org.richfaces.realworld.session;

import java.io.IOException;
import java.io.Serializable;

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

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.TransactionPropagationType;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.core.Events;
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.Album;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.fileupload.AvatarUpload;
import org.richfaces.realworld.fileupload.FileManager;
import org.richfaces.realworld.service.IUserAction;
import org.richfaces.realworld.tree.TreeSelectionManager;
import org.richfaces.realworld.util.NavigationEnum;

@Name("authenticator")
@Scope(ScopeType.CONVERSATION)
public class Authenticator implements Serializable
{
    @Logger Log log;
    
    @In Identity identity;
    
	@Out(required=false)
	private Image selectedImage;
	
	@Out(required=false)
	private User selectedUser;

	@Out(required=false)
	private Album selectedAlbum;
	
    @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()
    {
    	if(null == identity.getUsername() || identity.getUsername().equals("")){
    		identity.addRole("guest");
        	Events.instance().raiseEvent("updateMainArea", NavigationEnum.SEARCH);
        	userAction.loginAnonymous();
        	return true;
    	}
        try{
        	User user = userAction.login(identity.getUsername(), identity.getPassword());
        if(user != null){
        	identity.addRole("admin");
        	if(!fileManager.isDirectoryPresent(identity.getUsername())){
        		fileManager.addDirectory(identity.getUsername());
        	}
        	if(user.getChildAlbums().size() > 0){
        		selectedAlbum = user.getChildAlbums().get(0);
        		if(selectedAlbum.getImages().size() > 0){
        			selectedImage = selectedAlbum.getImages().get(0);
        		}
        	}
        	selectedUser = user;
        	/*for(User u:user.getFriends()){
        		for(Album a :u.getChildAlbums()){
        			a.getImages().get(0);
        		}
        	}
        	for(Album a:user.getSharedAlbums()){
        		a.getImages().get(0);
        	}*/
        	Events.instance().raiseEvent("updateMainArea", NavigationEnum.IMAGE_PREVIEW);
        	return true;
        }
        }catch(Exception nre){
        	facesMessages.add("Invalid login or password");
        	return false;
        }
        return false; 
    }
    
    @Begin @End
    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 "index";
    }
    
    /**
	 * Logout from session. 
	 * 
	 * @return outcome which redirects to login page. 
	 *//*
	public void logout() {
		Session.instance().invalidate();
	}*/
}
