package uk.ac.cam.caret.sakai.rwiki.tool.entityproviders;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import lombok.extern.slf4j.Slf4j;

import uk.ac.cam.caret.sakai.rwiki.service.api.PageLinkRenderer;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.ViewBean;
import uk.ac.cam.caret.sakai.rwiki.utils.NameHelper;
import uk.ac.cam.caret.sakai.rwiki.utils.XmlEscaper;

/**
 * Renders wiki links in the format /direct/wiki/site/SITEID/page/NAME
 *  
 * @author Adrian Fish <adrian.r.fish@gmail.com>
 */
@Slf4j
public class DirectServletPageLinkRenderer implements PageLinkRenderer {

	private boolean cachable = false;

	private boolean useCache = false;

	public String localRealm;

	public String localSpace;
	
	public String extension;

	public DirectServletPageLinkRenderer(String localRealm) {
		
		this(localRealm, localRealm,"json");
	}

	public DirectServletPageLinkRenderer(String localSpace, String localRealm, String extension) {
		
		this.localSpace = localSpace;
		this.localRealm = localRealm;
		this.extension = extension;
	}

	public void appendLink(StringBuffer buffer, String name, String view) {
		
		this.appendLink(buffer, name, view, null);
	}

	public void appendLink(StringBuffer buffer, String name, String view, String anchor) {
		
		name = NameHelper.globaliseName(name, localSpace);
		ViewBean vb = new ViewBean(name, localRealm);
		if (anchor != null && !"".equals(anchor)) 
		{
			vb.setAnchor(anchor);
		}
		
		try {
			buffer.append("<a class=\"wiki-page-link\" href=\"")
				.append("/direct/" + RWikiEntityProvider.ENTITY_PREFIX + localRealm + "/page/" + URLEncoder.encode(view,"UTF-8").replaceAll("\\+","%20") + "." + extension)
				.append("\">" + XmlEscaper.xmlEscape(view) + "</a>");
		} catch(UnsupportedEncodingException e) {
			log.error("UTF-8 is unsupported in the the encoding of URLs. The url was not appended.");
		}
	}

	public void appendCreateLink(StringBuffer buffer, String name, String view) {
	}

	public void setCachable(boolean cachable) {
		
		this.cachable = cachable;
	}

	public boolean isCachable() {
		
		return cachable;
	}

	public boolean canUseCache() {
		
		return useCache;
	}

	public void setUseCache(boolean useCache) {
		
		this.useCache = useCache;
	}

	public void appendLink(StringBuffer buffer, String name, String view, String anchor, boolean autoGenerated) {
		
		this.appendLink(buffer, name, view, anchor);
	}
}
