/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
package org.richfaces.realworld.manager;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.security.auth.login.LoginException;

import org.jboss.seam.ScopeType;
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.core.Conversation;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.web.Session;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.fileupload.FileManager;
import org.richfaces.realworld.service.Constants;
import org.richfaces.realworld.service.IUserAction;
import org.richfaces.realworld.util.ConversationState;

@Name("authenticator")
@Scope(ScopeType.CONVERSATION)
public class Authenticator implements Serializable
{

	@In("#{messages['invalid_login']}")
	private String INVALID_LOGIN_OR_PASSWORD;
	@In("#{messages['login_success']}")
	private String LOGIN_SUCCESS;
	
	@In("#{messages['user.exist']}") private String USER_WITH_THIS_LOGIN_ALREADY_EXIST;

	@In("#{messages['user.confirm.error']}") private String CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD;

	private static final long serialVersionUID = -4585673256547342140L;

	@Logger Log log;
	
    @In Identity identity;
    
    @In Credentials credentials;
	
    @In FacesMessages facesMessages;
    
    @In("#{conversation}") @Out 
    Conversation conversation;
    
    @In(create = true)
    IUserAction userAction;
    
    @In(create = true)
    FileManager fileManager;
    
	@In(create=true) @Out
	private ConversationState conversationState;

	public String login(){
		if(identity.hasRole("admin")){
			return "";
		}
		String password = credentials.getPassword();
		String username = credentials.getUsername();
		identity.unAuthenticate();
		credentials.setPassword(password);
		credentials.setUsername(username);
		try {
			identity.authenticate();
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	
    public boolean authenticate()
    {
    	
    	//System.out.print("FFFFFFFFFFFFuck");
    	if (wantLoginAnonymous()) {
			identity.addRole(Constants.GUEST_ROLE);
			userAction.loginAnonymous();
			//Events.instance().raiseEvent(Constants.UPDATE_MAIN_AREA_EVENT,NavigationEnum.SEARCH);
			return true;
		}
		try {
			User user = userAction.login(credentials.getUsername(), credentials.getPassword());
			if (user != null) {
				identity.addRole(Constants.ADMIN_ROLE);
				//setupCatalogForUser();
				//Events.instance().raiseEvent(Constants.UPDATE_MAIN_AREA_EVENT,NavigationEnum.IMAGE_PREVIEW);
				return true;
			}
		} catch (Exception nre) {
			facesMessages.add(INVALID_LOGIN_OR_PASSWORD);
			return false;
		}
		return false; 
    }
    
    @End
    public String register(User user){
    	if(checkPassword(user) || checkUserExist(user)){
    		return "";
    	}
    	userAction.register(user);
		facesMessages.add(LOGIN_SUCCESS);
    	return Constants.INDEX_OUTCOME;
    }

    public String logout(){
    	identity.logout();
    	identity.unAuthenticate();
    	credentials.clear();
    	//credentials.invalidate();
    	Session.instance().invalidate();
    	return "logout";
    }
    
    public String goToRegister(){
    	identity.logout();
    	identity.unAuthenticate();
    	credentials.clear();
    	credentials.invalidate();
    	return "register";
    }
    
    public String loginAnonymous(){
    	credentials.setUsername(null);
    	credentials.setPassword(null);
    	try {
			identity.authenticate();
		} catch (LoginException e) {
			facesMessages.add(INVALID_LOGIN_OR_PASSWORD);
			return "";
		}
    	return Constants.MAIN_OUTCOME;
    }
    
    public String start(){
    	//System.out.println("OOOOOO");
    	if(!identity.isLoggedIn()){
    		//identity.logout();
        	//identity.unAuthenticate();
        	credentials.clear();
        	//credentials.invalidate();
    		//conversation.begin();
        	try {
    			identity.authenticate();
    		} catch (LoginException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	return "";
    }

	private boolean wantLoginAnonymous() {
		return null == credentials.getUsername() || credentials.getUsername().equals("");
	}
	
	private boolean checkUserExist(User user) {
		if(userAction.isUserExist(user.getLogin())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent(Constants.REGISTER_LOGIN_NAME_ID);
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, USER_WITH_THIS_LOGIN_ALREADY_EXIST , USER_WITH_THIS_LOGIN_ALREADY_EXIST));
			return true;
    	}
		return false;
	}

	private boolean checkPassword(User user) {
		if(!user.getPassword().equals(user.getConfirmPassword())){
    		UIComponent root = FacesContext.getCurrentInstance().getViewRoot();
    		UIComponent component = root.findComponent(Constants.REGISTER_CONFIRM_PASSWORD_ID);
			FacesContext.getCurrentInstance().addMessage(component.getClientId(FacesContext.getCurrentInstance()), new FacesMessage(
					FacesMessage.SEVERITY_ERROR, CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD , CONFIRM_PASSWORD_NOT_EQUALS_PASSWORD));
			return true;
    	}
		return false;
	}
}
