/****************************************************************
 * 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: TwitterLearnerAction.java,v 1.21 2007/01/05 03:13:52 steven Exp $$ */
package org.lamsfoundation.lams.tool.twitter.web;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

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.apache.struts.util.MessageResources;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.tool.ToolAccessMode;
import org.lamsfoundation.lams.tool.ToolSessionManager;
import org.lamsfoundation.lams.tool.exception.DataMissingException;
import org.lamsfoundation.lams.tool.exception.ToolException;
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.TwitterUserTweet;
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.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.WebUtil;
import org.lamsfoundation.lams.web.action.LamsDispatchAction;
import org.lamsfoundation.lams.web.session.SessionManager;
import org.lamsfoundation.lams.web.util.AttributeNames;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;

/**
 * Creation Date: 29-06-05
 *  
 * This class has been created so that when a learner finishes an activity,
 * leaveToolSession() will be called to inform the progress engine
 * that the user has completed this activity.
 * 
 * A note: at the time of writing (11-08-05) a null pointer exception
 * occurs when making a call to leaveToolSession(). Will have to wait until
 * the learner side of things is tested first.
 * 
 * ----------------XDoclet Tags--------------------
 * 
 * @struts:action path="/learner" name="TwitterLearnerForm" scope="request" type="org.lamsfoundation.lams.tool.twitter.web.TwitterLearnerAction"
 *                input=".learnerContent" validate="false" parameter="method"
 * @struts:action-forward name="displayLearnerContent" path=".learnerContent"
 * @struts:action-forward name="reflectOnActivity" path=".reflectOnActivity"
 * @struts:action-forward name="learnerContentAction" path="/starter/learner.do?tweetMode=all"
 * ----------------XDoclet Tags--------------------
 */
public class TwitterLearnerAction extends LamsDispatchAction {

    static Logger logger = Logger.getLogger(TwitterLearnerAction.class.getName());

    /** Get the user id from the shared session */
	public Long getUserID(HttpServletRequest request) {
		// set up the user details
		HttpSession ss = SessionManager.getSession();
		UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
		if ( user == null )
		{
		    MessageResources resources = getResources(request);
		    String error = resources.getMessage(TwitterConstants.ERR_MISSING_PARAM, "User");
		    logger.error(error);
			throw new TwitterApplicationException(error);
		}
        return new Long(user.getUserID().longValue());
	}

    /**
     * Indicates that the user has finished viewing the twitter.
     * The session is set to complete and leaveToolSession is called.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward finish(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException, ToolException, DataMissingException, ServletException, IOException {
	
	  TwitterLearnerForm learnerForm = (TwitterLearnerForm)form;
	  Long userID = getUserID(request);
	  
	  Long toolSessionID = TwitterWebUtil.convertToLong(learnerForm.getToolSessionID());
	  if (toolSessionID == null)
	  {
	      String error = "Unable to continue. The parameters tool session id is missing";
	      logger.error(error);
	      throw new TwitterApplicationException(error);
	  }
	  
	  ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
	  ToolSessionManager sessionMgrService = TwitterServiceProxy.getTwitterSessionManager(getServlet().getServletContext());
		  
      ToolAccessMode mode = WebUtil.getToolAccessMode(learnerForm.getMode());
      if (mode == ToolAccessMode.LEARNER || mode == ToolAccessMode.AUTHOR)
	  {
		  TwitterSession twitterSession = twitterService.retrieveTwitterSession(toolSessionID);
		  TwitterUser twitterUser = twitterService.retrieveTwitterUserBySession(userID,toolSessionID);
		  
		  twitterUser.setUserStatus(TwitterUser.COMPLETED);
		  twitterService.updateTwitterSession(twitterSession);
		  twitterService.updateTwitterUser(twitterUser);
		  
		  // Create the notebook entry if reflection is set.
		  TwitterContent twitterContent = twitterService.retrieveTwitterBySessionID(toolSessionID);
		  if (twitterContent.getReflectOnActivity()) {
				// check for existing notebook entry
				NotebookEntry entry = twitterService.getEntry(toolSessionID,
						CoreNotebookConstants.NOTEBOOK_TOOL,
						TwitterConstants.TOOL_SIGNATURE, userID.intValue());

				if (entry == null) {
					// create new entry
					twitterService.createNotebookEntry(toolSessionID,
							CoreNotebookConstants.NOTEBOOK_TOOL,
							TwitterConstants.TOOL_SIGNATURE, userID
									.intValue(), learnerForm
									.getReflectionText());
				} else {
					// update existing entry
					entry.setEntry(learnerForm.getReflectionText());
					entry.setLastModified(new Date());
					twitterService.updateEntry(entry);
				}
			}
		  
		  String nextActivityUrl;
			try
			{
				nextActivityUrl = sessionMgrService.leaveToolSession(toolSessionID, getUserID(request));
			}
			catch (DataMissingException e)
			{
				log.error(e);
				throw new ServletException(e);
			}
			catch (ToolException e)
			{
				log.error(e);
				throw new ServletException(e);
			}
	        
			response.sendRedirect(nextActivityUrl);
			
	        return null;
		  
		  
	  }
	  request.setAttribute(TwitterConstants.READ_ONLY_MODE, "true");
	  

	  
	  return mapping.findForward(TwitterConstants.DISPLAY_LEARNER_CONTENT);
	  
	}
    
    /**
     * Indicates that the user has finished viewing the twitter, and will be
     * passed onto the Notebook reflection screen.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward reflect(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException {
	
    	ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
    	
    	TwitterLearnerForm learnerForm = (TwitterLearnerForm)form;
    	Long toolSessionID = TwitterWebUtil.convertToLong(learnerForm.getToolSessionID());
    	TwitterContent twitterContent = twitterService.retrieveTwitterBySessionID(toolSessionID);
    	request.setAttribute("reflectInstructions", twitterContent.getReflectInstructions());
    	request.setAttribute("title", twitterContent.getTitle());
    	
        // get the existing reflection entry
    	NotebookEntry entry = twitterService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, TwitterConstants.TOOL_SIGNATURE, getUserID(request).intValue());
        if (entry != null) {
        	request.setAttribute("reflectEntry", entry.getEntry());
        }
	  
    	return mapping.findForward(TwitterConstants.REFLECT_ON_ACTIVITY);
    }
    
    /**
     * Indicates that the user has finished viewing the twitter.
     * The session is set to complete and leaveToolSession is called.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException {
	
	HttpSession session = request.getSession(true);
	
	ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
	
	TwitterLearnerForm learnerForm = (TwitterLearnerForm)form;
	
	TwitterUser twitterUser = new TwitterUser();
	twitterUser.setUid(Long.parseLong(learnerForm.getUserID()));
	
	TwitterContent twitterContent = new TwitterContent(Long.parseLong(learnerForm.getContentID()));
	
	Twitter twitterInstance = new Twitter(session.getAttribute("twitterUsername").toString(), session.getAttribute("twitterPassword").toString());
	String pictureURL = twitterInstance.getUser(learnerForm.getTwitterUsername()).getProfileImageUrl().toString();
	
	TwitterUserTweet twitterUserTweet = new TwitterUserTweet(	twitterUser, 
												twitterContent,
												learnerForm.getTweet(),
												learnerForm.getTwitterUsername(),
												new Date(),
												pictureURL);
	
	try{
	    if(twitterInstance.isValidLogin()){
		twitterInstance.setStatus(learnerForm.getTweet());
		twitterService.saveTwitterUserTweet(twitterUserTweet);
		request.setAttribute("success", "El tweet se ha guardado con ˇxito!");
	    }
	    else{
		request.setAttribute("errors", "No se ha podido autentificar en twitter");
	    }
	}
	catch(TwitterException te){
	    request.setAttribute("errors", "No se ha podido guardar el tweet por el siguiente error: "+te.getAdditionalInfo());
	}

	return mapping.findForward(TwitterConstants.LEARNER_CONTENT_ACTION);
	
    }  
}
