/**
 * Copyright (c) 2004 Red Hat, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Component of: Red Hat Application Server
 * 
 * Initial Developers: Aizaz Ahmed
 *                     Vivek Lakshmanan
 *                     Andrew Overholt
 *                     Matthew Wringe
 *
 */
/*
 * Created on Sep 7, 2004
 *
 * 
 */
package olstore.session.helper;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Vector;
import olstore.entity.UserLocal;
import olstore.entity.UserLocalHome;
import olstore.entity.FriendLocal;
import olstore.entity.FriendLocalHome;
import olstore.entity.AddressLocal;
import olstore.entity.AddressLocalHome;
import olstore.dto.AddressValue;
import olstore.dto.CreateUserValue;
import olstore.dto.UserValue;
import olstore.framework.EJBHomeFactory;

import org.apache.commons.beanutils.BeanUtils;
/**
 * @ejb.bean name="UserHelper"
 *	type="Stateless" 
 *  view-type="local"
 *  local-jndi-name="UserHelperLocal_L"
 * 
 * @ejb.ejb-ref
 *  ejb-name="User"
 *  view-type="local"
 * 
 * @ejb.ejb-ref
 *  ejb-name="Address"
 *  view-type="local"
 * 
 * @ejb.ejb-ref
 *  ejb-name="Friend"
 *  view-type="local"
 * 
 * @ejb.transaction
 *  type="Required"
 * 
 *--
 * This is needed for JOnAS.
 * If you are not using JOnAS you can safely remove the tags below.
 * @jonas.bean ejb-name="UserHelper"
 * jndi-name="UserHelperLocal"
 * 
 *--
 **/

public abstract class UserHelperBean implements SessionBean {
    SessionContext ejbContext;
    
    // ------------------------------------------------------------------
    // SessionBean implementation
    // ------------------------------------------------------------------
    
    
    public void setSessionContext(SessionContext ctx) {
        ejbContext = ctx;
    }
    
    
    public void ejbRemove() {
    }
    
    
    public void ejbCreate() throws CreateException {
    }
    
    public void ejbPassivate() {
    }
    
    public void ejbActivate() {
    }
    
    
    // ------------------------------------------------------------------
    // UserHelper implementation
    // ------------------------------------------------------------------
    
    
    /**
     * Creates a collection of friends usernames and returns it.
     * 
     * @param user 	The user to get the collections from.
     * @return	A collection containing the username's of the user's friends
     */
    private Collection CalculateFriendsName (UserLocal user) throws Exception{
        Collection c= new Vector();
        Collection friends=user.getFriends();
        Iterator it= friends.iterator();
        while (it.hasNext()){
            c.add (((FriendLocal)it.next()).getUser().getUsername());
        }
        Collections.sort((Vector)c);
        return c;
    }
    
    /**
     * A Method to get and return a collection of usernames that are not
     * the user's username or that of any of there friend's usernames.
     * 
     * @param user	The user
     * @param friendsList	A collection of the user's friends username's
     * @return	A collection of usernames excluding the user's and there friend's usernames
     * @throws Exception
     */
    private Collection CalculateAllUsersList (UserLocal user, Collection friendsList) throws Exception {
        EJBHomeFactory factory = EJBHomeFactory.getInstance();
        UserLocalHome userHome=(UserLocalHome) factory.getLocalHome (EJBHomeFactory.USER);
        Collection allUsers= userHome.findAll();
        Iterator it=allUsers.iterator();
        Collection c=new Vector();
        String currentUser;
        while (it.hasNext()){
            currentUser=(((UserLocal)it.next()).getUsername());
            c.add(currentUser);
        }
        
        Collections.sort((Vector)c);
        
        //remove the users friends
        c.removeAll (friendsList);
        
        //remove the user from the collection
        c.remove(user.getUsername());
        
        return c;
    }
    
    
    /**
     * Method to copy the user's information from the
     * user entity bean to the userValue dto.
     * 
     * @param user The user to get the information from.
     * @return	The userValue dto.
     * @throws Exception
     * 
     * 
     * @ejb.interface-method
     */
    public UserValue UserToDTO (UserLocal user) throws Exception {
        UserValue userValue=new UserValue ();
        Collection friendsList=CalculateFriendsName(user);
        userValue.setFriendsList(friendsList);
        userValue.setAllUsersList (CalculateAllUsersList(user, friendsList));
        BeanUtils.copyProperties (userValue, user);
        return userValue;
    }
    
    
    /**
     * Used to save the user's information from a DTO back into 
     * the user entity bean
     * 
     * @param userValue The DTO storing the user information
     * @param addressValue The DTO storing the address information
     * @param username The username of the user
     * 
     * @ejb.interface-method
     */
    public void SaveUser (UserValue userValue, AddressValue addressValue, String username) throws Exception {
        EJBHomeFactory factory=EJBHomeFactory.getInstance();
        UserLocalHome userHome=(UserLocalHome)factory.getLocalHome (EJBHomeFactory.USER);
        UserLocal user=userHome.findByUsername (username);
        FriendLocalHome friendsHome=(FriendLocalHome)factory.getLocalHome (EJBHomeFactory.FRIENDS);
        AddressLocal address= user.getAddress();
        user.setLname (userValue.getLname());
        user.setFname (userValue.getFname());
        user.setEmailAdd (userValue.getEmailAdd());
        user.setPhoneNum (userValue.getPhoneNum());
        address.setCity(addressValue.getCity());
        address.setPostalCode(addressValue.getPostalCode());
        address.setStreet1(addressValue.getStreet1());
        address.setStreet2(addressValue.getStreet2());
        address.setCountry(addressValue.getCountry());
        address.setProvince(addressValue.getProvince());
        user.setAddress (address);
        
        
        Collection friends=user.getFriends();
        Iterator friendsIt=friends.iterator();
        
        //remove the old instances of friends
        while (friendsIt.hasNext()){
            FriendLocal friendsLoc=(FriendLocal)friendsIt.next();
            friendsIt.remove();
            friendsLoc.remove();
        }
        
        //load the new friends
        String[] newFriends=userValue.getFriendsListSelected();
        for (int i=0; i<newFriends.length;i++){
            friends.add (friendsHome.create (userHome.findByUsername (newFriends[i])));
        }
        user.setFriends (friends);
    }
    
    /**
     * Return the user's DTO when the username is passed to it
     * 
     * @param username The username of the user
     * @return The DTO for the user
     * 
     * @ejb.interface-method
     * 
     */
    public UserValue getUserValue (String username) throws Exception {
        EJBHomeFactory factory = EJBHomeFactory.getInstance();
        UserLocalHome userHome=(UserLocalHome) factory.getLocalHome (EJBHomeFactory.USER);
        UserLocal user = userHome.findByUsername (username);
        UserValue userValue= UserToDTO (user);
        return userValue;
    }
    
    /**
     *
     * 
     * Creates a new user entity bean
     * 
     * @param createUserValue  The DTO for the User
     * @param addressValue	The DTO for the User's Address
     * 
     * @ejb.interface-method
     * 
     */
    public void CreateUser (CreateUserValue createUserValue, AddressValue addressValue) throws Exception{
        EJBHomeFactory factory=EJBHomeFactory.getInstance();
        AddressLocalHome addressHome=null;
        addressHome=(AddressLocalHome)factory.getLocalHome(EJBHomeFactory.ADDRESS);
        UserLocalHome userHome=(UserLocalHome)factory.getLocalHome(EJBHomeFactory.USER);
        UserLocal user=userHome.create ( createUserValue.getUsername(), "customer",
                createUserValue.getLname(), createUserValue.getFname(), createUserValue.getEmailAdd(),
                createUserValue.getPhoneNum(), createUserValue.getPasswd1());
        AddressLocal address=addressHome.create ( addressValue.getCountry(), addressValue.getCity(),
                addressValue.getPostalCode(), addressValue.getStreet1(), addressValue.getStreet2(),
                addressValue.getProvince());
        user.setAddress (address);
    }
    
    
    
    
    
}
