package levik.weblet.lh;

import java.util.*;
import gnu.regexp.*;
import freemarker.template.*;

public class Feeling implements TemplateHashModel,java.io.Serializable {
    // Format: (M)M-DD-YYYY-HH-MM (HH: 24h format)
    private static final long serialVersionUID = 72320001514L;
    public static final int TEXT_LENGTH = 1000;
    public static final int NAME_LENGTH = 40;
    public static final int SUBJ_LENGTH = 60;

    protected String name;
    protected String object;
    protected String reason;
    protected Date date;
    protected static RE tagRemover;

    static {
	try {
	    tagRemover=new RE("(</[^aA][^>]*>)|(<[^/aA][^>]*>)");
	}
	catch (Exception e) {
	    e.printStackTrace();
	    tagRemover=null;
	}
    }

    public Feeling (String name, String object, String reason) {
	if (object==null || object.length()==0 || name==null || name.length()==0)
	    throw new IllegalArgumentException();
	this.name=trimToSize(tagRemove(name), NAME_LENGTH);
	this.object=trimToSize(tagRemove(object), SUBJ_LENGTH);
	this.reason=trimToSize(tagRemove(reason), TEXT_LENGTH);
	this.date=new Date();
    }

    public boolean isEmpty() {
	return false;
    }

    protected static String tagRemove(String text) {
	if (tagRemover==null || text.indexOf("<")<0) 
	    return text;
	System.err.println("about to substitute!!!!!!!!!!!!!!");
	return tagRemover.substituteAll(text," ");
    }

    public TemplateModel get(String key) {
	if (key==null) return null;
	else if (key.equals("name"))
	    return new SimpleScalar(trimToSize(name, NAME_LENGTH));
	else if (key.equals("object"))
	    return new SimpleScalar(trimToSize(object, SUBJ_LENGTH));
	else if (key.equals("encobject"))
	    return new SimpleScalar(java.net.URLEncoder.encode(trimToSize(object, SUBJ_LENGTH)));
	else if (key.equals("reason")) 
	    return new SimpleScalar(trimToSize(reason, TEXT_LENGTH));
	else if (key.equals("date")) 
	    return new SimpleScalar(date.toString());
	return null;
    }

    protected String trimToSize(String s, int size) {
        if (s == null) return null;
	if (s.length() <= size)
	    return s;
        return s.substring(0, size) + " ...";
    }
}
