/****************************************************************
 * 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: TwitterExportAction.java,v 1.12 2006/09/19 06:37:23 jliew Exp $$ */
package org.lamsfoundation.lams.tool.twitter.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.tool.twitter.TwitterApplicationException;
import org.lamsfoundation.lams.tool.twitter.TwitterConstants;
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.dto.ReflectionDTO;
import org.lamsfoundation.lams.tool.twitter.service.ITwitterService;
import org.lamsfoundation.lams.tool.twitter.service.TwitterServiceProxy;
import org.lamsfoundation.lams.tool.twitter.util.TwitterWebUtil;
import org.lamsfoundation.lams.web.action.LamsDispatchAction;


/**
 * @author mtruong
 *
 * Export Portfolio functionality.
 * 
 * With this twitter tool,
 * both the learner and teacher will export the contents of the twitter.
 * 
 */

/**
 * ----------------XDoclet Tags--------------------
 * 
 * @struts:action path="/exportPortfolio" name="TwitterExportForm" scope="request" type="org.lamsfoundation.lams.tool.twitter.web.TwitterExportAction"
 *                validate="false" parameter="mode"
 * @struts:action-forward name="exportPortfolio" path="/exportPortfolio.jsp"
 * ----------------XDoclet Tags--------------------
 */
public class TwitterExportAction extends LamsDispatchAction {
    
    static Logger logger = Logger.getLogger(TwitterExportForm.class.getName());

    public ActionForward unspecified(
    		ActionMapping mapping,
    		ActionForm form,
    		HttpServletRequest request,
    		HttpServletResponse response)
    {
        return mapping.findForward(TwitterConstants.EXPORT_PORTFOLIO);
    }
    
    public ActionForward learner(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
       //parameters given are the toolSessionId and userId
        TwitterExportForm exportForm = (TwitterExportForm)form;
        Long toolSessionId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.TOOL_SESSION_ID));
        Long userId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.USER_ID));
      
        
        ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
        
        if (userId == null || toolSessionId == null)
        {
            String error = "Tool session Id or user Id is null. Unable to continue";
            logger.error(error);
            throw new TwitterApplicationException(error);
        }
        
        TwitterUser userInThisSession = twitterService.retrieveTwitterUserBySession(userId, toolSessionId);
        
        if (userInThisSession == null)
        {
            String error="The user with user id " + userId + " does not exist in this session or session may not exist.";
            logger.error(error);
            throw new TwitterApplicationException(error);
        }
        
       TwitterContent content = twitterService.retrieveTwitterBySessionID(toolSessionId);
        
        if (content == null)
        {
            String error="The content for this activity has not been defined yet.";
            logger.error(error);
            throw new TwitterApplicationException(error);
        }
        
        // Get user's reflection if exists
        if (content.getReflectOnActivity()) {
        	log.debug(content.getReflectOnActivity());
        	request.setAttribute("learner", true);
        	NotebookEntry twitterEntry = twitterService.getEntry(userInThisSession.getTwitterSession().getTwitterSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, 
    			TwitterConstants.TOOL_SIGNATURE, userId.intValue());
        	log.debug(twitterEntry);
        	if (twitterEntry!=null) {
        		request.setAttribute("twitterEntry", twitterEntry.getEntry());
        	}
        }
               
        exportForm.populateForm(content);
       
        return mapping.findForward(TwitterConstants.EXPORT_PORTFOLIO);
    }
    
    public ActionForward teacher(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        //given the toolcontentId as a parameter
        TwitterExportForm exportForm = (TwitterExportForm)form;
        ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
        
        Long toolContentId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.TOOL_CONTENT_ID));
       
        //check if toolContentId exists in db or not
        if (toolContentId==null)
        {
            String error="Tool Content Id is missing. Unable to continue";
            logger.error(error);
            throw new TwitterApplicationException(error);
        }
        
        TwitterContent content = twitterService.retrieveTwitter(toolContentId);
        
        if (content == null)
        {
            String error="Data is missing from the database. Unable to Continue";
            logger.error(error);
            throw new TwitterApplicationException(error);
        }
        
        // Get class's reflections if exists
        if (content.getReflectOnActivity()) {
        	Set sessions = content.getTwitterSessions();
            Iterator i = sessions.iterator();
            List<ReflectionDTO> reflections = new ArrayList<ReflectionDTO>();
            while (i.hasNext())
            {
            	TwitterSession session = (TwitterSession) i.next();
                List sessionUsers = twitterService.getUsersBySession(session.getTwitterSessionId());
                for (int j=0; j<sessionUsers.size(); j++) {
                	TwitterUser twitterUser = (TwitterUser)sessionUsers.get(j);
                	NotebookEntry twitterEntry = twitterService.getEntry(twitterUser.getTwitterSession().getTwitterSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, 
                   			TwitterConstants.TOOL_SIGNATURE, twitterUser.getUserId().intValue());
                	log.debug(twitterEntry);
                	if (twitterEntry!=null) {
                		ReflectionDTO dto = new ReflectionDTO(twitterEntry);
                		dto.setFullName(twitterUser.getFullname());
                		reflections.add(dto);
                	}
                }
            }
            request.setAttribute("reflections", reflections);
        }
        
        exportForm.populateForm(content);
  
   		return mapping.findForward(TwitterConstants.EXPORT_PORTFOLIO);
    }
    
    
}
