/****************************************************************
 * 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.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
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.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.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="/twitter" name="TwitterLearnerTwitterForm" scope="request" type="org.lamsfoundation.lams.tool.twitter.web.TwitterLearnerTwitterAction"
 *                validate="false" parameter = "method"
 * @struts:action-forward name="loginTwitter" path=".loginTwitter"
 * @struts:action-forward name="successTwitter" path="/starter/learner.do?tweetMode=all"
 * ----------------XDoclet Tags--------------------
 */
public class TwitterLearnerTwitterAction extends LamsDispatchAction {

    /**
     * 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 show(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException, ToolException, DataMissingException, ServletException, IOException {

	TwitterContent twitterContent = null;
	TwitterLearnerTwitterForm twitterForm = (TwitterLearnerTwitterForm)form;
	
	Long toolSessionID = TwitterWebUtil.convertToLong(twitterForm.getToolSessionID());
	
	ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
	
	twitterContent = twitterService.retrieveTwitterBySessionID(toolSessionID);
	
	twitterForm.copyValuesIntoForm(twitterContent.getTitle());
	
	return mapping.findForward(TwitterConstants.LOGIN_TWITTER);  
    }
    
    
    /**
     * 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 login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException, ToolException, DataMissingException, ServletException, IOException {
	
	TwitterLearnerTwitterForm twitterForm = (TwitterLearnerTwitterForm)form;
	
	ActionErrors errors = twitterForm.validate(mapping, request);
	
	if(errors.size() == 0){
	    
	    if(validateLogin(twitterForm.getTwitterUsername(), twitterForm.getTwitterPassword())){

		HttpSession session = request.getSession(true);
		session.setAttribute("twitterUsername", twitterForm.getTwitterUsername());
		session.setAttribute("twitterPassword", twitterForm.getTwitterPassword());
		
		return mapping.findForward(TwitterConstants.SUCCESS_TWITTER);
	    }
	    else{
		errors.add("", new ActionMessage("error.twitter.login.failed"));
	    }
	}
	
	ActionMessage actionMessage= (ActionMessage)errors.get().next();
	
	request.setAttribute("errors", actionMessage.getKey());
	    
	twitterForm.setTwitterUsername("");
	twitterForm.setTwitterPassword("");
	
	return mapping.findForward(TwitterConstants.LOGIN_TWITTER);  
    }
    
    /**
     * 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 logout(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException, ToolException, DataMissingException, ServletException, IOException {
	
	HttpSession session = request.getSession(true);
	session.removeAttribute("twitterUsername");
	session.removeAttribute("twitterPassword");
	
	return mapping.findForward(TwitterConstants.LOGIN_TWITTER);
	
    }
    
    private boolean validateLogin(String username, String password){
	Twitter twitter = new Twitter(username, password);
	
	//try{
	    if(twitter.isValidLogin()){
		return true;
	    }
	    else{
		return false;
	    }
	//}
	//catch(TwitterException.Timeout t){
	//    return false;
	//}
    }
}
