package com.rjlresaka.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

@WebServlet("/app/groups/create")
public class CreateGroupServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final ConversationDAO conversationDAO = new ConversationDAO();

    @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");
        String groupName = request.getParameter("groupName");
        String[] selectedMembers = request.getParameterValues("memberIds");
        List<Integer> memberIds = new ArrayList<Integer>();
        if (selectedMembers != null) {
            for (String value : selectedMembers) {
                int id = parseInt(value);
                if (id > 0) {
                    memberIds.add(Integer.valueOf(id));
                }
            }
        }

        if (memberIds.isEmpty()) {
            session.setAttribute("flashError", "Choisissez au moins un ami pour créer un groupe.");
            response.sendRedirect(request.getContextPath() + "/app/dashboard");
            return;
        }

        try {
            int conversationId = conversationDAO.createGroupConversation(authUser.getId(), groupName, memberIds, getServletContext());
            session.setAttribute("flashSuccess", "Groupe créé avec succès.");
            response.sendRedirect(request.getContextPath() + "/app/dashboard?conversation=" + conversationId);
        } catch (Exception exception) {
            session.setAttribute("flashError", "Création du groupe impossible : " + exception.getMessage());
            response.sendRedirect(request.getContextPath() + "/app/dashboard");
        }
    }

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