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

public class ModifyUserStatusAction extends ZalleryAction{

	public ModifyUserStatusAction() {
		super("moduser", 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 // set target user to the logged in user
			target_user = user;

		if( user.canEdit(target_user) ){
			if( request.getParameter("email") != null )
				target_user.setEmail( request.getParameter("email") );
			if( request.getParameter("password") != null ){
				if( target_user.getPassword() == null )
					target_user.setPassword( request.getParameter("password") );
				else if( request.getParameter("oldPassword") != null )
					if( target_user.equalsPassword(request.getParameter("oldPassword")) )
						target_user.setPassword( request.getParameter("password") );
					else{									
						if(out != null)	out.println("{ \"error\": \"Wrong password!\"}");
						else			msgs.add(MessageType.ERROR, "Wrong password!");
						return;
					}
			}
			if( request.getParameter("name") != null )
				target_user.setName( request.getParameter("name") );
			target_user.save(db);
			if( !user.isEmailVerified() )
				ZalleryEmail.sendVerificationEmail( target_user );
			if( out != null ) 
				out.println("{ }");
			else
				msgs.add(MessageType.INFO, "Settings saved successfully.");
		}
		else if(out != null)	out.println("{ \"error\": \"You are not authorize to change these values!\"}");
		else					msgs.add(MessageType.ERROR, "You are not authorize to change these values!");
	}

}
