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.Zallery;
import zall.action.ZalleryAction;
import zall.bean.User;
import zall.util.ZalleryEmail;
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;

public class ModifyUserAction extends ZalleryAction{

	public ModifyUserAction() {
		super("moduserstat", true);
	}

	@Override
	public void handleRequest(DBConnection db, HttpServletRequest request, HttpServletResponse response, HttpSession session,
			PrintWriter out, User user, UserMessage msgs) throws SQLException, IOException {

		// Administration things of users
		if( user.isSuperUser() ){
			User target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
			// Enable user
			if( request.getParameter("enable") != null ){
				target_user.setEnabled( true );
				// Email the user about the activation
				ZalleryEmail.sendActivationEmail(target_user);
			}
			// Disable user, can not disable one self!
			else if( request.getParameter("disable") != null && !user.equals( target_user ) )
				target_user.setEnabled( false );
			// Promote user to Admin
			else if( request.getParameter("setadmin") != null )
				target_user.setSuperUser( true );
			// Degrade Admin to normal user, can not degrade one self!
			else if( request.getParameter("unadmin") != null && !user.equals( target_user ) )
				target_user.setSuperUser( false );
			else{
				if( out != null ) out.println("{ }");
				return;
			}
			target_user.save(db);
			if( out != null ) 
				out.println("{ }");
			else 
				msgs.add(MessageType.INFO, "Account changes saved.");
			return;
		}
	}

}
