package zall.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Logger;

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

import zall.action.ZalleryAction;
import zall.bean.User;
import zall.util.ZalleryEmail;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;
import zutil.log.LogUtil;

public class SendVerificationEmailAction extends ZalleryAction{
	private static final Logger logger = LogUtil.getLogger();

	public SendVerificationEmailAction() {
		super("sendverfemail", true);
	}

	@Override
	public void handleRequest(DBConnection db, HttpServletRequest request, HttpServletResponse response, HttpSession session,
			PrintWriter out, User user, UserMessage msgs) throws SQLException, IOException {
		
		User target_user = null;
		if( request.getParameter("id") != null )
			target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
		else {
			if(out != null)	out.println("{ \"error\": \"Missing parameters!\"}");
			else			msgs.add(MessageType.ERROR, "Missing parameters!");
			return;
		}

		if( target_user != null ){
			if( user.isSuperUser() ){
				ZalleryEmail.sendVerificationEmail(target_user);
				
				logger.info("Verification email sent successfully to: "+user.getEmail());
				if( out != null ) 	out.println("{ }");
				else				msgs.add(MessageType.INFO, "Verification email sent successfully.");
			}
			else if(out != null)	out.println("{ \"error\": \"You are not authorize send verification emails!\"}");
			else					msgs.add(MessageType.ERROR, "You are not authorize send verification emails!");
		}
		else {
			if(out != null)	out.println("{ \"error\": \"No such user!\"}");
			else			msgs.add(MessageType.ERROR, "No such user!");
		}
	}

}
