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.FriendDAO;
import com.rjlresaka.model.User;

@WebServlet("/app/friends/request")
public class FriendRequestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final FriendDAO friendDAO = new FriendDAO();

    @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 receiverId = parseInt(request.getParameter("receiverId"));
        try {
            friendDAO.sendRequest(authUser.getId(), receiverId, getServletContext());
            session.setAttribute("flashSuccess", "Demande d'ami envoyée.");
        } catch (Exception exception) {
            session.setAttribute("flashError", "Impossible d'envoyer la demande : " + exception.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/app/dashboard");
    }

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