package com.rjlresaka.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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 javax.servlet.http.Part;

import com.rjlresaka.dao.MessageDAO;
import com.rjlresaka.model.Message;
import com.rjlresaka.model.StoredAttachment;
import com.rjlresaka.model.User;
import com.rjlresaka.util.FileStorageUtil;

@WebServlet("/app/messages/send")
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 10 * 1024 * 1024, maxRequestSize = 12 * 1024 * 1024)
public class SendMessageServlet 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 partnerId = parseInt(request.getParameter("partnerId"));
        String body = trim(request.getParameter("body"));

        Part attachmentPart = request.getPart("attachment");
        try {
            StoredAttachment attachment = FileStorageUtil.store(attachmentPart, getServletContext());
            if (body.isEmpty() && attachment == null) {
                setFlash(session, "flashError", "Ajoutez un texte ou un fichier avant d'envoyer.");
                response.sendRedirect(request.getContextPath() + redirectTarget(conversationId, partnerId));
                return;
            }

            Message draft = new Message();
            draft.setBody(body);
            if (attachment != null) {
                draft.setAttachmentName(attachment.getOriginalName());
                draft.setAttachmentPath(attachment.getStoragePath());
                draft.setAttachmentType(attachment.getContentType());
                draft.setAttachmentSize(attachment.getSize());
            }

            if (conversationId > 0) {
                messageDAO.createMessageInConversation(authUser.getId(), conversationId, draft, getServletContext());
            } else if (partnerId > 0) {
                conversationId = messageDAO.createMessage(authUser.getId(), partnerId, draft, getServletContext());
            } else {
                setFlash(session, "flashError", "Conversation introuvable.");
                response.sendRedirect(request.getContextPath() + "/app/dashboard");
                return;
            }
            setFlash(session, "flashSuccess", "Message envoyé.");
        } catch (Exception exception) {
            setFlash(session, "flashError", "Envoi impossible pour le moment : " + exception.getMessage());
        }
        response.sendRedirect(request.getContextPath() + "/app/dashboard?conversation=" + conversationId);
    }

    private String redirectTarget(int conversationId, int partnerId) {
        if (conversationId > 0) {
            return "/app/dashboard?conversation=" + conversationId;
        }
        if (partnerId > 0) {
            return "/app/dashboard?user=" + partnerId;
        }
        return "/app/dashboard";
    }

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

    private String trim(String value) {
        return value == null ? "" : value.trim();
    }

    private void setFlash(HttpSession session, String key, String message) {
        session.setAttribute(key, message);
    }
}
