/**
 * 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.security.auth.login.LoginException;

import org.jboss.seam.ScopeType;
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.web.RequestParameter;
import org.jboss.seam.contexts.Contexts;
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.service.Constants;
import org.richfaces.realworld.service.IUserAction;
import org.richfaces.realworld.ui.PasswordHolder;

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

	@In ShelfManager shelfManager;
	
	@In("#{messages['invalid_login']}")
	private String INVALID_LOGIN_OR_PASSWORD;

	@RequestParameter protected Long startConversation;
	
	private static final long serialVersionUID = -4585673256547342140L;

	@In PasswordHolder passwordHolder;
	
	@Logger Log log;
	
    @In Identity identity;
    
    @Out(required=false) User user;
    @In Credentials credentials;
	
    @In FacesMessages facesMessages;
    
    @In("#{conversation}") @Out 
    Conversation conversation;
    
    @In IUserAction userAction;
    
    @In FileManager fileManager;
	
	@In @Out Model model;

	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();
			shelfManager.clearShelfs();
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "main";
	}
	
    public boolean authenticate()
    {
    	if (wantLoginAnonymous()) {
			identity.addRole(Constants.GUEST_ROLE);
			model.setMainArea(NavigationEnum.ANONYM);
			return true;
		}
		try {
			user = userAction.login(credentials.getUsername(), passwordHolder.hash(credentials.getPassword()));
			if (user != null) {
				identity.addRole(Constants.ADMIN_ROLE);
				model.resetModel(NavigationEnum.ALL_SHELFS, user, null, null, null);
				return true;
			}
		} catch (Exception nre) {
			facesMessages.add(INVALID_LOGIN_OR_PASSWORD);
			return false;
		}
		return false; 
    }

    public String logout(){
    	identity.logout();
    	identity.unAuthenticate();
    	credentials.clear();
    	Session.instance().invalidate();
    	return "logout";
    }
    
    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(){
    	if(!identity.isLoggedIn()){
        	credentials.clear();
        	try {
    			identity.authenticate();
    		} catch (LoginException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	return "";
    }

    public String startConversation(){
    	identity.logout();
		identity.unAuthenticate();
		credentials.clear();
		return "";
    }
    
	private boolean wantLoginAnonymous() {
		return null == credentials.getUsername() || credentials.getUsername().equals("");
	}

	public Long getStartConversation() {
		return startConversation;
	}
}
