package com.rjlresaka.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rjlresaka.dao.MessageDAO;
import com.rjlresaka.model.User;

@WebServlet("/app/messages/react")
public class ToggleReactionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final MessageDAO messageDAO = new MessageDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("authUser") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        User authUser = (User) session.getAttribute("authUser");
        int conversationId = parseInt(request.getParameter("conversationId"));
        int messageId = parseInt(request.getParameter("messageId"));
        String emoji = request.getParameter("emoji");

        try {
            messageDAO.toggleReaction(messageId, authUser.getId(), emoji, getServletContext());
        } catch (Exception exception) {
            session.setAttribute("flashError", "Réaction indisponible : " + exception.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/app/dashboard?conversation=" + conversationId);
    }

    private int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}
