package zall.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;

public class RemoveUserAction extends ZalleryAction{

	public RemoveUserAction() {
		super("rmuser", true);
	}

	@Override
	public void handleRequest(DBConnection db, HttpServletRequest request, HttpServletResponse response, HttpSession session,
			PrintWriter out, User user, UserMessage msgs) throws SQLException, IOException {
		
		// Remove user
		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() ){
				target_user.delete(db);
				
				if( out != null ) 	out.println("{ }");
				else				msgs.add(MessageType.INFO, "User removed successfully.");
			}
			else if(out != null)	out.println("{ \"error\": \"You are not authorize to delete that user!\"}");
			else					msgs.add(MessageType.ERROR, "You are not authorize to delete that user!");
		}
		else {
			if(out != null)	out.println("{ \"error\": \"No such user!\"}");
			else			msgs.add(MessageType.ERROR, "No such user!");
		}
	}

}
