// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package dk.vajhoej.forum;

import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.ValueFormatException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.version.VersionManager;

public class ForumManager {
	// use dash instead of space and special characters in path parts
	static String nameFixUp(String name) {
		return name.replaceAll("[ /]", "-").replaceAll("[^A-Za-z0-9#-]", "");
	}
	// number formats:
	//   #n
	//   #n.m
	private String getAutoNumber(Node parent) throws ValueFormatException, PathNotFoundException, RepositoryException, ForumException {
		String num = Long.toString(parent.getNodes("*").getSize() + 1);
		if(isPost(parent)) {
			return "#" + num;
		} else if(isComment(parent)) {
			return parent.getProperty("number").getString() + "." + num;
		} else {
			throw new ForumException("Comment parent is neither post nor comment");
		}
	}
	// check that can be used to avoid duplicates
	private boolean alreadyHasChild(Node parent, String nodename) throws RepositoryException {
		return parent.getNodes(nodename).getSize() > 0;
	}
	// a permanent open session per ForumManager instance
	private Session ses;
	public ForumManager(Repository repo, String usr, String pwd) throws RepositoryException {
		// login
		this.ses = repo.login(new SimpleCredentials(usr, pwd.toCharArray()));
		// ensure forum root exists
		if(!ses.getRootNode().hasNode("F")) {
			ses.getRootNode().addNode("F");
		}
	}
	Session getSession() {
		return ses;
	}
	// test nodes
	boolean isTopic(Node n) throws RepositoryException {
		return n.hasProperty("name") && n.hasProperty("description");
	}
	boolean isPost(Node n) throws RepositoryException {
		return n.hasProperty("title") && n.hasProperty("body") && n.hasProperty("author");
	}
	boolean isComment(Node n) throws RepositoryException {
		return n.hasProperty("number") && n.hasProperty("text") && n.hasProperty("author");
	}
	// find nodes
	Node getAnyNode(String path) throws PathNotFoundException, RepositoryException {
		return ses.getRootNode().getNode(path.substring(1));
	}
	// add nodes
	public String addTopic(String topicName, String topicDescription) throws RepositoryException {
		Node parent = getAnyNode("/F");
		String nodename = nameFixUp(topicName);
		if(!alreadyHasChild(parent, nodename)) {
			Node child = parent.addNode(nodename);
			child.setProperty("name", topicName);
			child.setProperty("description", topicDescription);
    		ses.save();
    		return "/F/" + nodename;
		} else {
			return null;
		}
	}
	public String addPost(String path, String postTitle, String postBody, String postAuthor) throws RepositoryException, ForumException {
		Node parent = getAnyNode(path);
		if(!isTopic(parent)) {
			throw new ForumException("Trying to add post to non-topic");
		}
		String nodename = nameFixUp(postTitle);
		if(!alreadyHasChild(parent, nodename)) {
			Node child = parent.addNode(nodename);
			child.addMixin(NodeType.MIX_VERSIONABLE);
			child.setProperty("title", postTitle);
			child.setProperty("body", postBody);
			child.setProperty("author", postAuthor);
			child.setProperty("time", System.currentTimeMillis());
    		ses.save();
    		return path + "/" + nodename;
		} else {
			return null;
		}
	}
	public String addComment(String path, String commentNumber, String commentText, String commentAuthor) throws RepositoryException, ForumException {
		Node parent = getAnyNode(path);
		if(!isPost(parent) && !isComment(parent)) {
			throw new ForumException("Trying to add comment to non-post and non-comment");
		}
		String nodename = nameFixUp(commentNumber);
		if(!alreadyHasChild(parent, nodename)) {
			Node child = parent.addNode(nodename);
			child.addMixin(NodeType.MIX_VERSIONABLE);
			child.setProperty("number", commentNumber);
			child.setProperty("text", commentText);
			child.setProperty("author", commentAuthor);
			child.setProperty("time", System.currentTimeMillis());
			ses.save();
    		return path + "/" + nodename;
		} else {
			return null;
		}
	}
	public String addCommentAutoNumber(String path, String commentText, String commentAuthor) throws RepositoryException, ForumException {
		String cn = getAutoNumber(getAnyNode(path));
		return addComment(path, cn, commentText, commentAuthor);
	}
	// update nodes
	public void updatePost(String path, String newPostBody) throws RepositoryException, ForumException {
		VersionManager vm = ses.getWorkspace().getVersionManager();
		// if first update save original version
		if(vm.getVersionHistory(path).getAllVersions().getSize() <= 1) {
			vm.checkout(path);
			ses.save();
			vm.checkin(path);
			ses.save();
		}
		// checkout
		vm.checkout(path);
		ses.save();
		// update
		Node node = getAnyNode(path);
		if(!isPost(node)) {
			throw new ForumException("Updating non-post as post");
		}
		node.setProperty("body", newPostBody);
		node.setProperty("time", System.currentTimeMillis());
		ses.save();
		// checkin
		vm.checkin(path);
		ses.save();
	}
	public void updateComment(String path, String newCommentText) throws RepositoryException, ForumException {
		VersionManager vm = ses.getWorkspace().getVersionManager();
		// if first update save original version
		if(vm.getVersionHistory(path).getAllVersions().getSize() <= 1) {
			vm.checkout(path);
			ses.save();
			vm.checkin(path);
			ses.save();
		}
		// checkout
		vm.checkout(path);
		ses.save();
		// update
		Node node = getAnyNode(path);
		if(!isComment(node)) {
			throw new ForumException("Updating non-comment as comment");
		}
		node.setProperty("text", newCommentText);
		node.setProperty("time", System.currentTimeMillis());
		ses.save();
		// checkin
		vm.checkin(path);
		ses.save();
	}
}
