package zall;

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

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

import zall.action.*;
import zall.action.media.*;
import zall.action.user.*;
import zall.bean.*;
import zutil.net.smtp.Email;
import zutil.net.smtp.Email.ContentType;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;
import zutil.log.LogUtil;

public class ZalleryAjax extends HttpServlet{
	public static final Logger logger = LogUtil.getLogger();
	private static final long serialVersionUID = 1L;

	private HashMap<String,ZalleryAction> actions;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		// General
		registerAction(new LoginAction());
		registerAction(new RegisterAction());

		// User Actions
		registerAction(new ModifyUserAction());
		registerAction(new ModifyUserStatusAction());
		registerAction(new RemoveUserAction());
		registerAction(new SendVerificationEmailAction());
		registerAction(new VerifyEmailAction());

		// Media Actions
		registerAction(new CommentAction());
		registerAction(new CreateFolderAction());
		registerAction(new ModifyMediaAction());
		registerAction(new RemoveFolderAction());
		registerAction(new RemoveMediaAction());
		registerAction(new TogglePrivateAction());
	}

	protected void registerAction(ZalleryAction action){
		if(actions == null)
			actions = new HashMap<>();
		actions.put(action.getActionId().toLowerCase(), action);
	}

	public  void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		try {
			doGet(request, response, response.getWriter());
		} catch (IOException e) {
			throw new ServletException(e);
		}
	}

	public  void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		doGet(request, response, null);
	}

	/**
	 * @param 		out		is the PrintStream that will be used, no output will be generated if it is null
	 */
	private  void doGet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException{
		DBConnection db = null;
		try {
			String actionStr = request.getParameter("action").toLowerCase();
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			db = Zallery.getDB();
			UserMessage msgs = UserMessage.getUserMessage(session);


			ZalleryAction action = actions.get( actionStr );
			if( action != null ){
				if( (action.requireUser() && user != null) || !action.requireUser() ){
					action.handleRequest(db, request, response, session, out, user, msgs);
				}
				else{
					// Unauthorized
					if( out != null ){
						out.print( "{\"error\":\"Unauthorized user!\"}" );
						response.setStatus( 401 );					
					}
					else
						msgs.add(MessageType.ERROR, "Unauthorized user!");
					logger.severe("Unauthorized user!");
					return;
				}
			}
			else{
				// Unauthorized
				if( out != null ){
					out.print( "{\"error\":\"Unknown action!\"}" );
					response.setStatus( 404 );					
				}
				else
					msgs.add(MessageType.ERROR, "Unknown action: '"+actionStr+"'!");
				logger.severe("Unknown action: '"+actionStr+"'!");
				return;
			}

		} catch (Exception e) {
			if( out != null ){
				out.println("{\"error\":\""+e.getMessage().replaceAll("\"", "\\\"")+"\"}");
				logger.log(Level.SEVERE, "Exception in ajax page!", e);
			}				
			else
				throw new ServletException(e);
		} finally{
			if(db != null) db.close();
		}
	}
}
