/****************************************************************
 * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org)
 * =============================================================
 * License Information: http://lamsfoundation.org/licensing/lams/2.0/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2.0 
 * as published by the Free Software Foundation.
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 * 
 * http://www.gnu.org/licenses/gpl.txt
 * ****************************************************************
 */

/* $$Id: TwitterSessionDAO.java,v 1.10 2006/09/17 06:26:26 fmalikoff Exp $$ */
package org.lamsfoundation.lams.tool.twitter.dao.hibernate;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.lamsfoundation.lams.tool.twitter.TwitterContent;
import org.lamsfoundation.lams.tool.twitter.TwitterSession;
import org.lamsfoundation.lams.tool.twitter.TwitterUser;
import org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author mtruong
 * <p>Hibernate implementation for database access to Twitter sessions for the twitter tool.</p>
 */

public class TwitterSessionDAO extends HibernateDaoSupport implements ITwitterSessionDAO {
	
	private static final String FIND_NB_SESSION = "from " + TwitterSession.class.getName() + " as twitter where twitter.twitterSessionId=?";
	
    private static final String LOAD_NBSESSION_BY_USER = "select ns from TwitterSession ns left join fetch "
        + "ns.twitterUsers user where user.userId=:userId";
    
    private static final String GET_SESSIONS_FROM_CONTENT = "select ns.twitterSessionId from TwitterSession ns where ns.twitterContent= :twitterContent";
  
	
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#findTwitterSessionById(java.lang.Long) */
    public TwitterSession findTwitterSessionById(Long twitterSessionId)
	{
	    String query = "from TwitterSession twitterS where twitterS.twitterSessionId=?";
	    List session = getHibernateTemplate().find(query,twitterSessionId);
		
		if(session!=null && session.size() == 0)
		{			
			return null;
		}
		else
		{
			return (TwitterSession)session.get(0);
		}
	}
	
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#saveTwitterSession(org.lamsfoundation.lams.tool.twitter.TwitterSession) */
    public void saveTwitterSession(TwitterSession twitterSession)
    {
    	this.getHibernateTemplate().save(twitterSession);
    }
    
	
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#updateTwitterSession(org.lamsfoundation.lams.tool.twitter.TwitterSession) */
    public void updateTwitterSession(TwitterSession twitterSession)
    {
    	this.getHibernateTemplate().update(twitterSession);
    }

 
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#removeTwitterSession(java.lang.Long) */
    public void removeTwitterSession(Long twitterSessionId)
    {
       
    	HibernateTemplate templ = this.getHibernateTemplate();
		if ( twitterSessionId != null) {
			//String query = "from org.lamsfoundation.lams.tool.twitter.TwitterContent as twitter where twitter.twitterContentId=?";
			List list = getSession().createQuery(FIND_NB_SESSION)
				.setLong(0,twitterSessionId.longValue())
				.list();
			
			if(list != null && list.size() > 0){
				TwitterSession twitter = (TwitterSession) list.get(0);
				this.getSession().setFlushMode(FlushMode.AUTO);
				templ.delete(twitter);
				templ.flush();
			}
		}
      
    }
    
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#removeTwitterSession(org.lamsfoundation.lams.tool.twitter.TwitterSession) */
    public void removeTwitterSession(TwitterSession twitterSession)
    {
    	removeTwitterSession(twitterSession.getTwitterSessionId());
        //this.getHibernateTemplate().delete(twitterSession);
    }

    
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#getTwitterSessionByUser(java.lang.Long) */
    public TwitterSession getTwitterSessionByUser(final Long userId)
	{
		 return (TwitterSession) getHibernateTemplate().execute(new HibernateCallback()
                {

                    public Object doInHibernate(Session session) throws HibernateException
                    {
                        return session.createQuery(LOAD_NBSESSION_BY_USER)
                                      .setLong("userId",
                                      		userId.longValue())
                                      .uniqueResult();
                    }
                });
	}
	
	 
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#removeTwitterUsers(org.lamsfoundation.lams.tool.twitter.TwitterSession) */
    public void removeTwitterUsers(TwitterSession twitterSession)
    {
    	this.getHibernateTemplate().deleteAll(twitterSession.getTwitterUsers());
    }
	
    
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#addTwitterUsers(java.lang.Long, org.lamsfoundation.lams.tool.twitter.TwitterSession) */
    public void addTwitterUsers(Long twitterSessionId, TwitterUser user)
	{
	    TwitterSession session = findTwitterSessionById(twitterSessionId);
	    user.setTwitterSession(session);
	    session.getTwitterUsers().add(user);
	    this.getHibernateTemplate().saveOrUpdate(user);
	    this.getHibernateTemplate().merge(session);	    
	}
	
    /** @see org.lamsfoundation.lams.tool.twitter.dao.ITwitterSessionDAO#getSessionsFromContent(org.lamsfoundation.lams.tool.twitter.TwitterSession) */
	public List getSessionsFromContent(TwitterContent twitterContent)
	{
	    return (getHibernateTemplate().findByNamedParam(GET_SESSIONS_FROM_CONTENT,
	            "twitterContent",
				twitterContent));
	}
    	
}
