// Package 
package gov.va.med.esr.ui.common.action;

// Java Classes
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

// Library Classes
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.commons.lang.Validate;
import gov.va.med.esr.ui.admin.action.UserSessionsAbstractAction;
import gov.va.med.fw.util.StringUtils;

/**
 * Action handler for sending an Async. Message.
 *
 * @author Andrew Pach
 * @version: 3.0
 */
public class SendAsyncMessageAction extends UserSessionsAbstractAction
{
    // Request parameters
    public static final String SESSION_ID_PARAM = "sessionId";
    public static final String MESSAGE_PARAM = "message";
    public static final String FROM_USERNAME_PARAM = "fromUsername";
    public static final String TO_USERNAME_PARAM = "toUsername";

    // XML Tags
    public static final String ROOT_ELEMENT_START = "<message>";
    public static final String ROOT_ELEMENT_END = "</message>";
    public static final String USER_MESSAGE_START = "<userMessage>";
    public static final String USER_MESSAGE_END = "</userMessage>";
    public static final String VALUE_START = "<value>";
    public static final String VALUE_END = "</value>";

    /**
     * Gets any async messages.
     * @param mapping The ActionMapping
     * @param form The ActionForm
     * @param request The HttpServletRequest
     * @param response The HttpServletResponse
     * @return The ActionForward
     * @throws Exception if any problems were encountered
     */
    public ActionForward sendAsyncMessage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the session Id from the request
        String sessionId = request.getParameter(SESSION_ID_PARAM);

        // Get the message from the request
        String message = request.getParameter(MESSAGE_PARAM);

        // Get the "from username from the request
        String fromUsername = request.getParameter(FROM_USERNAME_PARAM);

        // Get the "to" username from the request
        String toUsername = request.getParameter(TO_USERNAME_PARAM);

        // Assign a username of unknown if one wasn't specified
        if (StringUtils.isBlank(fromUsername))
        {
            fromUsername = "[UNKNOWN]";
        }
        if (StringUtils.isBlank(toUsername))
        {
            toUsername = "[UNKNOWN]";
        }

        // Ensure the required fields were passed
        Validate.notNull(message, "No message was found on the sendAsyncMessage request.");

        // Update the actual message to send
        String sendMessage = "Message from user " + fromUsername + ": '" + message + "'.";

        String xml = null;

        // Send the message to the appropriate users
        if (StringUtils.isBlank(sessionId))
        {
            // If no session Id is present, send out a broadcast user to all users
            broadcastAsyncMessage(request, sendMessage);
            xml = buildResponseXml("Broadcast message successfully placed in queue for all users: '" + message + "'.");
        }
        else
        {
            if (getSessionById(request, sessionId) != null)
            {
                // Send a message to the user in the specified session Id
                sendAsyncMessage(request, sessionId, sendMessage);
                xml = buildResponseXml("Message successfully placed in queue for user " + toUsername + ": '" +
                    message + "'.");
            }
            else
            {
                // The session isn't valid
                xml = buildResponseXml("Unable to send message to user " + toUsername + " because their session was " +
                    "not found: '" + message + "'.");
            }
        }

        // Write the XML to the response
        response.setContentType("text/xml");
        response.setHeader("Cache-Control","no-cache");
        PrintWriter out = response.getWriter();
        out.println(xml);
        out.flush();

        // Return null so Struts doesn't do anything
        return null;
    }

    /**
     * Builds the response XML message
     * @param returnMessage the return message to the user requesting the message to be sent
     * @return The response XML message
     */
    protected String buildResponseXml(String returnMessage)
    {
        StringBuffer xml = new StringBuffer();
        xml.append(ROOT_ELEMENT_START);
        if (StringUtils.isNotBlank(returnMessage))
        {
            xml.append(USER_MESSAGE_START);

            // Enclose the message in start and end tags so the caller can
            // easily determine that a message is present
            xml.append(VALUE_START);
            xml.append(returnMessage);
            xml.append(VALUE_END);

            xml.append(USER_MESSAGE_END);
        }
        xml.append(ROOT_ELEMENT_END);
        return xml.toString();
    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet()
    {
    }
}
