// 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 java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.ValueFormatException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;

import dk.vajhoej.forum.model.Comment;
import dk.vajhoej.forum.model.Forum;
import dk.vajhoej.forum.model.Post;
import dk.vajhoej.forum.model.Topic;

public class ModelMapper {
	private Topic nodeToTopic(Node n) throws ValueFormatException, PathNotFoundException, RepositoryException {
		return new Topic(n.getProperty("name").getString(),
				         n.getProperty("description").getString());
	}
	private Post nodeToPost(Node n) throws ValueFormatException, PathNotFoundException, RepositoryException {
		return new Post(n.getProperty("author").getString(), 
                        new Date(n.getProperty("time").getLong()),
                        n.getProperty("title").getString(),
                        n.getProperty("body").getString());
	}
	private Comment nodeToComment(Node n) throws ValueFormatException, PathNotFoundException, RepositoryException {
		return new Comment(n.getProperty("author").getString(), 
                           new Date(n.getProperty("time").getLong()),
                           n.getProperty("number").getString(),
                           n.getProperty("text").getString());
	}
	private void loadTopics(List<Topic> topics, boolean recurse) throws RepositoryException, ForumException {
		NodeIterator it = fmgr.getSession().getRootNode().getNode("F").getNodes("*");
		while(it.hasNext()) {
			Node n = it.nextNode();
			if(fmgr.isTopic(n)) {
				Topic t = nodeToTopic(n);
				topics.add(t);
				if(recurse) {
					loadPosts(t.getPosts(), n, true);
				}
			} else {
				throw new ForumException("Forum has non-topic child");
			}
		}
	}
	private void loadPosts(List<Post> posts, Node parent, boolean recurse) throws RepositoryException, ForumException {
		if(!fmgr.isTopic(parent)) {
			throw new ForumException("Trying to get posts of non-topic");
		}
		NodeIterator it = parent.getNodes("*");
		while(it.hasNext()) {
			Node n = it.nextNode();
			if(fmgr.isPost(n)) {
				Post p = nodeToPost(n);
				posts.add(p);
				VersionManager vm = fmgr.getSession().getWorkspace().getVersionManager();
				VersionHistory vhist = vm.getVersionHistory(n.getPath());
				VersionIterator vit = vhist.getAllVersions();
				while(vit.hasNext()) {
					Version v = vit.nextVersion();
					NodeIterator vnit = v.getNodes();
					while(vnit.hasNext()) {
						Node vn = vnit.nextNode();
						if(fmgr.isPost(vn)) {
							p.getVersions().add(nodeToPost(vn));
						}
					}
				}
				if(recurse) {
					loadComments(p.getComments(), n, true);
				}
			} else {
				throw new ForumException("Topic has non-post child");
			}
		}
	}
	private void loadComments(List<Comment> comments, Node parent, boolean recurse) throws RepositoryException, ForumException {
		if(!fmgr.isPost(parent) && !fmgr.isComment(parent)) {
			throw new ForumException("Trying to get comemnts of non-topic and non-comment");
		}
		NodeIterator it = parent.getNodes("*");
		while(it.hasNext()) {
			Node n = it.nextNode();
			if(fmgr.isComment(n)) {
				Comment c = nodeToComment(n);
				comments.add(c);
				VersionManager vm = fmgr.getSession().getWorkspace().getVersionManager();
				VersionHistory vhist = vm.getVersionHistory(n.getPath());
				VersionIterator vit = vhist.getAllVersions();
				while(vit.hasNext()) {
					Version v = vit.nextVersion();
					NodeIterator vnit = v.getNodes();
					while(vnit.hasNext()) {
						Node vn = vnit.nextNode();
						if(fmgr.isComment(vn)) {
							c.getVersions().add(nodeToComment(vn));
						}
					}
				}
				if(recurse) {
					loadComments(c.getComments(), n, true);
				}
			} else {
				throw new ForumException("Post/comment has non-comment child");
			}
		}
	}
	// mapping between model and JCR
	private ForumManager fmgr;
	public ModelMapper(ForumManager fmgr) {
		this.fmgr = fmgr;
	}
	// load
	public Forum loadForum() throws RepositoryException, ForumException {
		Forum f = new Forum();
		loadTopics(f.getTopics(), true);
		return f;
	}
	public Topic loadTopic(String path, boolean recurse) throws PathNotFoundException, RepositoryException, ForumException {
		Node n = fmgr.getAnyNode(path);
		if(fmgr.isTopic(n)) {
			Topic t = nodeToTopic(n);
			if(recurse) {
				loadPosts(t.getPosts(), n, true);
			}
			return t;
		} else {
			throw new ForumException("Path is not a topic path: " + path);
		}
	}
	public Topic loadTopic(String path) throws PathNotFoundException, RepositoryException, ForumException {
		return loadTopic(path, false);
	}
	public Post loadPost(String path, boolean recurse) throws PathNotFoundException, RepositoryException, ForumException {
		Node n = fmgr.getAnyNode(path);
		if(fmgr.isPost(n)) {
			Post p = nodeToPost(n);
			if(recurse) {
				loadComments(p.getComments(), n, true);
			}
			return p;
		} else {
			throw new ForumException("Path is not a post path: " + path);
		}
	}
	public Post loadPost(String path) throws PathNotFoundException, RepositoryException, ForumException {
		return loadPost(path, false);
	}
	public Comment loadComment(String path, boolean recurse) throws PathNotFoundException, RepositoryException, ForumException {
		Node n = fmgr.getAnyNode(path);
		if(fmgr.isComment(n)) {
			Comment c = nodeToComment(n);
			if(recurse) {
				loadComments(c.getComments(), n, true);
			}
			return c;
		} else {
			throw new ForumException("Path is not a comment path: " + path);
		}
	}
	public Comment loadComment(String path) throws PathNotFoundException, RepositoryException, ForumException {
		return loadComment(path, false);
	}
	// search
	public List<Post> findPostByAuthor(String author, boolean recurse) throws RepositoryException, ForumException {
		List<Post> res = new ArrayList<>();
		Query q = fmgr.getSession().getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:unstructured] WHERE author = $author AND title IS NOT NULL AND number IS NULL", Query.JCR_SQL2);
		q.bindValue("author", fmgr.getSession().getValueFactory().createValue(author));
		QueryResult qr = q.execute();
		NodeIterator nit = qr.getNodes();
		while(nit.hasNext()) {
			Node n = nit.nextNode();
			if(fmgr.isPost(n)) {
				Post p = nodeToPost(n);
				res.add(p);
				if(recurse) {
					loadComments(p.getComments(), n, true);
				}
			}
		}
		return res;
	}
	public List<Post> findPostByAuthor(String author) throws RepositoryException, ForumException {
		return findPostByAuthor(author, false);
	}
	public List<Post> findPostByContent(String content, boolean recurse) throws RepositoryException, ForumException {
		List<Post> res = new ArrayList<>();
		Query q = fmgr.getSession().getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:unstructured] WHERE CONTAINS(body,$content) AND title IS NOT NULL AND number IS NULL", Query.JCR_SQL2);
		q.bindValue("content", fmgr.getSession().getValueFactory().createValue(content));
		QueryResult qr = q.execute();
		NodeIterator nit = qr.getNodes();
		while(nit.hasNext()) {
			Node n = nit.nextNode();
			if(fmgr.isPost(n)) {
				Post p = nodeToPost(n);
				res.add(p);
				if(recurse) {
					loadComments(p.getComments(), n, true);
				}
			}
		}
		return res;
	}
	public List<Post> findPostByContent(String content) throws RepositoryException, ForumException {
		return findPostByContent(content, false);
	}
	public List<Comment> findCommentByAuthor(String author, boolean recurse) throws RepositoryException, ForumException {
		List<Comment> res = new ArrayList<>();
		Query q = fmgr.getSession().getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:unstructured] WHERE author = $author AND title IS NULL AND number IS NOT NULL", Query.JCR_SQL2);
		q.bindValue("author", fmgr.getSession().getValueFactory().createValue(author));
		QueryResult qr = q.execute();
		NodeIterator nit = qr.getNodes();
		while(nit.hasNext()) {
			Node n = nit.nextNode();
			if(fmgr.isComment(n)) {
				Comment c = nodeToComment(n);
				res.add(c);
				if(recurse) {
					loadComments(c.getComments(), n, true);
				}
			}
		}
		return res;
	}
	public List<Comment> findCommentByAuthor(String author) throws RepositoryException, ForumException {
		return findCommentByAuthor(author, false);
	}
	public List<Comment> findCommentByContent(String content, boolean recurse) throws RepositoryException, ForumException {
		List<Comment> res = new ArrayList<>();
		Query q = fmgr.getSession().getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:unstructured] WHERE CONTAINS(text,$content) AND title IS NULL AND number IS NOT NULL", Query.JCR_SQL2);
		q.bindValue("content", fmgr.getSession().getValueFactory().createValue(content));
		QueryResult qr = q.execute();
		NodeIterator nit = qr.getNodes();
		while(nit.hasNext()) {
			Node n = nit.nextNode();
			if(fmgr.isComment(n)) {
				Comment c = nodeToComment(n);
				res.add(c);
				if(recurse) {
					loadComments(c.getComments(), n, true);
				}
			}
		}
		return res;
	}
	public List<Comment> findCommentByContent(String content) throws RepositoryException, ForumException {
		return findCommentByContent(content, false);
	}
}
