package zall.page;

import zall.Zallery;
import zall.ZalleryServlet;
import zall.bean.User;
import zall.manager.AuthenticationManager;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import zutil.ui.UserMessageManager;
import zutil.ui.UserMessageManager.MessageLevel;
import zutil.ui.UserMessageManager.UserMessage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Logger;

@WebServlet(ProfileServlet.URI)
public class ProfileServlet extends ZalleryServlet {
    private static Logger logger = LogUtil.getLogger();

    public static final String URI = "/profile";
    private static final String JSP_FILE = "page_profile.jsp";


    public void doGet(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws ServletException, IOException, SQLException {
        UserMessageManager msgs = Zallery.getUserMessage(request.getSession());
        User user = AuthenticationManager.getUserSession(request.getSession());

        if (request.getParameter("id") != null) {
            User profile_user = User.load(db, Long.parseLong(request.getParameter("id")));
            if (AuthenticationManager.canEdit(user, profile_user)) {
                request.setAttribute("profile_user", profile_user);
            } else {
                msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("user.modify.not.allowed")));
            }
        } else {
            request.setAttribute("profile_user", user);
        }

        include(JSP_FILE, request, response);

    }


    public void doPost(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws SQLException, IOException, ServletException {
        doGet(request, response, db);
    }
}
