package org.apache.jetspeed.om.dbpsml;

// JDK classes
import java.util.List;
import java.sql.Connection;


// Jetspeed classes for Database PsmlManager implementation
import org.apache.jetspeed.services.psmlmanager.db.DBUtils;

// Turbine classes
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.turbine.util.RunData;

//Torque classes
import org.apache.torque.util.Criteria;
import org.apache.torque.util.BasePeer;


// Local classes
import org.apache.jetspeed.om.dbpsml.map.*;

// Jetspeed classes (Profiler)
import org.apache.jetspeed.services.Profiler;

import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.om.profile.ProfileLocator;
import org.apache.jetspeed.services.psmlmanager.db.DBOperations;
import org.apache.jetspeed.services.psmlmanager.db.DBUtils;
import org.apache.jetspeed.services.psmlmanager.db.DatabasePsmlManager;
import org.apache.jetspeed.services.PsmlManager;

/**
  * The skeleton for this class was autogenerated by Torque on:
  *
  * [Mon Sep 10 13:30:53 PDT 2001]
  *
  *  You should add additional methods to this class to meet the
  *  application requirements.  This class will only be generated as
  *  long as it does not already exist in the output directory.
  *
  * @author <a href="mailto:adambalk@cisco.com">Atul Dambalkar</a>
  * @version $Id: JetspeedUserProfilePeer.java,v 1.14 2003/07/23 19:50:14 morciuch Exp $
  */
public class JetspeedUserProfilePeer
    extends org.apache.jetspeed.om.dbpsml.BaseJetspeedUserProfilePeer
    implements DBOperations
{

    /**
     * Default constructor.
     */
    public JetspeedUserProfilePeer() {}


    /**
     * Insert a user profile record in the database table.
     *
     * @param profile Profile object that will be inserted in the database
     * @param connection A database connection to use
     */
    public void insert(Profile profile, Connection connection) throws Exception
    {
        doInsertOrUpdate(profile, INSERT, connection);
    }

    /**
     * Insert a user profile record in the database table.
     *
     * @param profile Profile object that will be inserted in the database
     * @param connection A database connection to use
     */
    public void update(Profile profile, Connection connection) throws Exception
    {
        doInsertOrUpdate(profile, UPDATE, connection);
    }

    private void doInsertOrUpdate(Profile profile, int operation, Connection connection)
                         throws Exception
    {
        JetspeedUserProfile userProfile = new JetspeedUserProfile();
        DatabasePsmlManager service = (DatabasePsmlManager)PsmlManager.getService();

        userProfile.setUserName(profile.getUser().getUserName());
        userProfile.setMediaType(profile.getMediaType());
        
        String language = profile.getLanguage();
        if(language != null && (!language.equals("-1")))
        {
			userProfile.setLanguage(language);
        }
        else
        {
        	userProfile.setLanguage(null);
        }
        
        String country = profile.getCountry();
        if(country != null && (!country.equals("-1")))
        {
			userProfile.setCountry(country);
        }
        else
        {
        	userProfile.setCountry(null);
        }

        
        String name = profile.getName();
        if (name == null || name.equals(""))
        {
            profile.setName(Profiler.FULL_DEFAULT_PROFILE);
        }
        else if (!name.endsWith(Profiler.DEFAULT_EXTENSION))
        {
            profile.setName(name + Profiler.DEFAULT_EXTENSION);
        }
        userProfile.setPage(profile.getName());
        userProfile.setProfile(DBUtils.portletsToBytes(
                                        profile.getDocument().getPortlets(), service.getMapping()));

        if (operation == INSERT)
        {
            super.doInsert(userProfile, connection);
        }
        else if (operation == UPDATE)
        {
            Criteria values = buildCriteria(userProfile);
            Criteria select = buildCriteria(userProfile);
            select.remove(PROFILE);
            BasePeer.doUpdate( select, values, connection );
        }
    }


    /**
     * Delete user profile record from the database table.
     *
     * @param profile Profile object that will be deleted from the database
     * @param connection A database connection to use
     */
    public void delete(ProfileLocator locator, Connection connection) throws Exception
    {
        super.doDelete(buildCriteria(locator), connection);
    }

    /**
     * Select user profile record from the database table for the given
     * locator object.
     *
     * @param locator ProfileLocator object that will be used to select required
     * profile from the database
     * @param connection A database connection to use
     * @return List of records that statisfy the given locator criteria.
     */
    public List select(ProfileLocator locator, Connection connection) throws Exception
    {
        Criteria criteria = buildCriteria(locator);
        return super.doSelect(criteria, connection); // buildCriteria(locator));
    }

    /**
     * Select user profile record from the database table for the given
     * locator object and return list ordered by primary key.
     *
     * @param locator ProfileLocator object that will be used to select required
     * profile from the database
     * @param connection A database connection to use
     * @return List of records that statisfy the given locator criteria.
     */
    public List selectOrdered(ProfileLocator locator, Connection connection) throws Exception
    {
        Criteria criteria = buildCriteria(locator);

        criteria.addAscendingOrderByColumn(USER_NAME);
        criteria.addAscendingOrderByColumn(MEDIA_TYPE);
        criteria.addAscendingOrderByColumn(LANGUAGE);
        criteria.addAscendingOrderByColumn(COUNTRY);
        criteria.addAscendingOrderByColumn(PAGE);

        return super.doSelect(criteria, connection);
    }


    /**
     * Delete all records from the database table for a user.
     *
     * @param user User object for which all the records will be deleted from the database
     * @param connection A database connection to use
     */
    public void delete(JetspeedUser user, Connection connection) throws Exception
    {
        Criteria criteria = new Criteria();

        criteria.add(USER_NAME, user.getUserName());

        super.doDelete(criteria, connection);
    }

    /*
     * Build criteria for selecting, deleting groups
     *
     */
    protected Criteria buildCriteria(ProfileLocator locator)
    {
        Criteria criteria = new Criteria();

        String mediaType = locator.getMediaType();
        String language = locator.getLanguage();
        String country = locator.getCountry();
        String pageName = locator.getName();
        String userName = null;
        JetspeedUser user= locator.getUser();

        if (user != null) {
            userName = user.getUserName();
        }

        if (userName != null && userName.length() > 0)
        {
            criteria.add(USER_NAME, userName) ;
        }

        if (pageName != null && pageName.length() > 0)
        {
            criteria.add(PAGE, pageName);
        }

        if (mediaType != null && mediaType.length() > 0)
        {
            criteria.add(MEDIA_TYPE, mediaType);
        }

        if (language != null && language.length() > 0 && (!language.equals("-1")))
        {
        	criteria.add(LANGUAGE, language);
        } 
        else if(language != null && language.equals("-1"))
        {
        	criteria.add(LANGUAGE, null);	
        }

        if (country != null && country.length() > 0 && (!country.equals("-1")))
        {
        	criteria.add(COUNTRY, country);
        }
		else if(country != null && country.equals("-1"))
		{
			criteria.add(COUNTRY, null);	
		}
        return criteria;
    }
}

