/****************************************************************
 * 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: TwitterMonitoringAction.java,v 1.27 2008/07/21 06:07:19 lfoxton 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.util.WebUtil;
import org.lamsfoundation.lams.web.action.LamsDispatchAction;
import org.lamsfoundation.lams.web.util.AttributeNames;

/**
 * @author mtruong
 * 
 * The buttons are a switch between tabs and will forward to a jsp and display
 * the appropriate page.
 * 
 *
 */

/**
 * Creation Date: 14-07-05
 *  
 * ----------------XDoclet Tags--------------------
 * 
 * @struts:action path="/monitoring" name="TwitterMonitoringForm" scope="request" type="org.lamsfoundation.lams.tool.twitter.web.TwitterMonitoringAction"
 *                input=".monitoringContent" validate="false" parameter="method"
 * @struts:action-forward name="monitorPage" path="/monitoring/monitoring.jsp"
 * @struts:action-forward name="monitorReflectionPage" path=".monitorReflectionPage"
 * ----------------XDoclet Tags--------------------
 */
public class TwitterMonitoringAction extends LamsDispatchAction {
    
    static Logger logger = Logger.getLogger(TwitterMonitoringAction.class.getName());
    
    public final static String FORM="TwitterMonitoringForm";
    
    public static final String SUMMARY_TABID = "1";
    public static final String INSTRUCTIONS_TABID = "2";
    public static final String EDITACTIVITY_TABID = "3";
    public static final String STATISTICS_TABID = "4";
   
    public ActionForward unspecified(
    		ActionMapping mapping,
    		ActionForm form,
    		HttpServletRequest request,
    		HttpServletResponse response) throws TwitterApplicationException
    {
    	Long toolContentId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.TOOL_CONTENT_ID));
        String contentFolderID = WebUtil.readStrParam(request, TwitterConstants.CONTENT_FOLDER_ID);
    	if (toolContentId == null)
 		{
 		    String error = "Unable to continue. Tool content id missing";
 		    logger.error(error);
 			throw new TwitterApplicationException(error);
 		}
         
        TwitterMonitoringForm monitorForm = new TwitterMonitoringForm();

        ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
		TwitterContent content = twitterService.retrieveTwitter(toolContentId);

    	monitorForm.setTitle(content.getTitle());
    	monitorForm.setContent(content.getContent());
    	monitorForm.setOnlineInstructions(content.getOnlineInstructions());
    	monitorForm.setOfflineInstructions(content.getOfflineInstructions());
		monitorForm.setAttachmentsList(TwitterWebUtil.setupAttachmentList(twitterService, content));

		monitorForm.setContentEditable("true");
	    //set up the request parameters to append to the URL
	    Map<String,Object> mapParameters = new HashMap<String,Object>();
	    mapParameters.put(TwitterConstants.TOOL_CONTENT_ID, toolContentId.toString());
	    mapParameters.put(TwitterConstants.DEFINE_LATER, "true");
	    mapParameters.put(TwitterConstants.CONTENT_FOLDER_ID, contentFolderID);
	    monitorForm.setParametersToAppend(mapParameters);
		
        //Get the total number of learners that have participated in this tool activity
        monitorForm.setTotalLearners(twitterService.calculateTotalNumberOfUsers(toolContentId));
        
        Set sessions = content.getTwitterSessions();
        Iterator i = sessions.iterator();
        Map map = new HashMap();
        List<ReflectionDTO> reflections = new ArrayList<ReflectionDTO>();
        while (i.hasNext())
        {
        	TwitterSession session = (TwitterSession) i.next();
            int numUsersInSession = twitterService.getNumberOfUsersInSession(session);
            map.put(session.getTwitterSessionName(), new Integer(numUsersInSession));
            // Get list of users that have made a reflection entry 
            if (content.getReflectOnActivity()) {
            	List sessionUsers = twitterService.getUsersBySession(session.getTwitterSessionId());
            	for (int j=0; j<sessionUsers.size(); j++) {
            		TwitterUser twitterUser = (TwitterUser)sessionUsers.get(j);
            		NotebookEntry twitterEntry = twitterService.getEntry(session.getTwitterSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, 
                			TwitterConstants.TOOL_SIGNATURE, twitterUser.getUserId().intValue());
            		if (twitterEntry!=null) {
            			ReflectionDTO dto = new ReflectionDTO(twitterEntry);
            			dto.setExternalId(session.getTwitterSessionId());
            			dto.setUserId(twitterUser.getUserId());
            			dto.setUsername(twitterUser.getUsername());
            			reflections.add(dto);
            		}
            	}
            }
        }
        monitorForm.setGroupStatsMap(map);
        
        // Set reflection statistics, if reflection is set
        request.setAttribute("reflectOnActivity", content.getReflectOnActivity());
        request.setAttribute("reflectInstructions", content.getReflectInstructions());
        request.setAttribute("reflections", reflections);
        
        String currentTab = WebUtil.readStrParam(request, AttributeNames.PARAM_CURRENT_TAB,true);
   		monitorForm.setCurrentTab(currentTab != null? currentTab : SUMMARY_TABID);
        request.setAttribute(FORM, monitorForm);
   		return mapping.findForward(TwitterConstants.MONITOR_PAGE);
    }
	    
    public ActionForward viewReflection (
    		ActionMapping mapping,
    		ActionForm form,
    		HttpServletRequest request,
    		HttpServletResponse response) throws TwitterApplicationException
    {
    	Long userId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.USER_ID));
    	Long toolSessionId = TwitterWebUtil.convertToLong(request.getParameter(TwitterConstants.TOOL_SESSION_ID));
    	ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
    	TwitterUser twitterUser = twitterService.retrieveTwitterUser(userId, toolSessionId);
    	NotebookEntry twitterEntry = twitterService.getEntry(twitterUser.getTwitterSession().getTwitterSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, 
    			TwitterConstants.TOOL_SIGNATURE, userId.intValue());
    	if (twitterEntry!=null) {
    		request.setAttribute("twitterEntry", twitterEntry.getEntry());
    		request.setAttribute("name", twitterUser.getFullname());
    	}
    	
    	return mapping.findForward(TwitterConstants.MONITOR_REFLECTION_PAGE);
    }
   
}
