package com.amarda.framework.taglib;

import org.apache.struts.taglib.template.util.*;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.http.HttpServletRequest;


public class MessageTag extends org.apache.struts.taglib.bean.MessageTag {

  private String role;
  private String prefix = "";
  private String suffix = "";
  private String template;

  public String getPrefix() {
    return prefix;
  }
  public void setPrefix(String newPrefix) {
    prefix = newPrefix;
  }
  public String getSuffix() {
    return suffix;
  }
  public void setSuffix(String newSuffix) {
    suffix = newSuffix;
  }
  public String getTemplate() {
    return template;
  }
  public void setTemplate(String newTemplate) {
    template = newTemplate;
  }

  public String getRole() {
      return role;
  }
  public void setRole(String role) {
     this.role = role;
  }

  public int doStartTag() throws JspException {

     // Check the role
     HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
     if(role != null && !request.isUserInRole(role))
     	return SKIP_BODY;

     // Construct the Key
     String generatedKey = prefix + templateGet() + suffix;

     // Construct the optional arguments array we will be using
     Object args[] = new Object[5];
     args[0] = arg0;
     args[1] = arg1;
     args[2] = arg2;
     args[3] = arg3;
     args[4] = arg4;

     // Retrieve the message string we are looking for
     String message = RequestUtils.message(pageContext, this.bundle,
                                              this.localeKey, generatedKey, args);
     if (message == null) {
	    JspException e = new JspException
		(messages.getMessage("message.message", key));
            RequestUtils.saveException(pageContext, e);
            throw e;
     }

     // Print the retrieved message to our output writer
     ResponseUtils.write(pageContext, message);

     // Continue processing this page
     return (SKIP_BODY);
  }

  protected String templateGet() throws JspException {

     ContentMap  map = ContentMapStack.peek(pageContext);
     Content content = map.get(template);

     if (content == null) {
       return "";
     }

     if(content.isDirect()) {
        return content.toString();
     } else {
        throw new JspException("msgTag: template content must be direct");
     }

  }

  public void release() {
    super.release();
    prefix = "";
    suffix = "";
    template = null;
    role = null;
  }
}