<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page import="org.crosswire.community.projects.ntmss.data.Document" %>
<%@ page import="org.crosswire.utils.Utils" %>
<%@ page import="org.crosswire.utils.HTTPUtils" %>
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="javax.validation.constraints.Pattern" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Collections" %>
<%@ page import="org.crosswire.webtools.annotation.*" %>
<%@ page import="org.crosswire.webtools.*" %>

<%!
@Description(value = "Retrieve bibliographical material associated with a manuscript.", name = "bibliography/get")
public static class MyParameters extends Parameters<MyParameters> {

	@Description(value = "manuscript ID to query", example = "10046")
	public Integer docID = null;

	@Description(value = "manuscript primary name to query", example = "P46")
	public String gaNum = null;

	@Pattern(regexp = "^(xhtml|rss|json)?$", message = "Valid response formats: \"xhtml\", \"rss\", or \"json\"")
	@Description(value = "Specify the result format: xhtml, rss, json", defaultValue = "xhtml", example = "json")
	public String format = null;

	@Override
	protected void customValidation() {
		
		if (gaNum != null) {
			Document doc = Document.getDocumentByGANumber(gaNum);
			if (doc != null) {
				docID = doc.getDocumentID();
			}
			else addError(-5, "{gaNum} supplied could not be found.");
		}
		if (docID == null) {
			addError(-4, "Must provide at least one of: {docID}, {gaNum}.");
			return;
		}
	}
}
%>
<%
MyParameters params = new MyParameters().loadFromRequest(request, response, false);

if (params.getErrors().size() == 0) {

	//String style = "chicago-note-biblio-no-ibid";
	//String style = "chicago-fullnote-bibliography";
	String style = "apa";
	int chunkMax = 100;

	String zoteroAPIKey = Utils.getSysConfig(session).getProperty("ZoteroAPIKey");
	String zoteroUser = Utils.getSysConfig(session).getProperty("ZoteroUser");
	boolean biblioAddJKElliot = "true".equals(Utils.getSysConfig(session).getProperty("BiblioAddJKElliot"));
	params.getLogger().debug("zoteroAPIKey="+zoteroAPIKey);
	params.getLogger().debug("zoteroUser="+zoteroUser);

	if (params.format == null) params.format = "xhtml";

	String zFormat = "keys";
	if ("rss".equals(params.format)) zFormat="atom";
	if ("json".equals(params.format)) zFormat="json";
	if ("keys".equals(params.format)) zFormat="keys";

	Document doc = Document.getDocument(params.docID);

	do {
	if (doc == null) {
		params.addError(-6, "docID: (" + params.docID + ") not found.");
		break;
	}

	if (zFormat.equals("json")) {
		response.setContentType("text/json");
	}
	else if (zFormat.equals("atom")) {
		response.setContentType("text/xml");
	}
	else {
		response.setContentType("text/html");
	}

	String url = "https://api.zotero.org/users/"+zoteroUser+"/items/";

	String zParams = "tag="+doc.getDocumentID();
	zParams +=       "&key="+zoteroAPIKey;
	zParams +=       "&format="+zFormat;

	try {
		HTTPUtils.Response r = new HTTPUtils.Response();
		StringBuffer z = HTTPUtils.postURL(url, zParams, HTTPUtils.GET, r);
		if ("Invalid key".equals(z.toString().trim())) {
			params.getLogger().warn("Bibliographic service not configured properly with a Zortero API key. See sysconfig.properties");
			// don't output anything to user, but let admin know in log
			return;
		}
		if (r.resultCode < 0) {
			params.getLogger().warn("Bibliographic service returned an error code (" + r.resultCode + "). See sysconfig.properties to assure proper configuration");
			// don't output anything to user, but let admin know in log
			return;
		}

		if ("keys".equals(zFormat)) {
			StringBuffer keys = new StringBuffer();
			String ks[] = z.toString().split("\\s+");
			int size = ks.length;
			int chunkSize = 0;
			z = new StringBuffer();
			List<String> entries = new ArrayList<String>();
//params.getLogger().info("bibliography: size: "+size);
			for (String k: ks) {
				keys.append(k+",");
				++chunkSize;
				--size;
				if (chunkSize == chunkMax || size == 0) {
					String p = "itemKey="+keys.toString();
					p +=       "&key="+zoteroAPIKey;
					p +=       "&format=bib";
					p +=       "&style="+style;
//params.getLogger().info("bibliography: sending: "+p);
					HTTPUtils.Response r2 = new HTTPUtils.Response();
					StringBuffer y = HTTPUtils.postURL(url, p, HTTPUtils.GET, r2);
//params.getLogger().info("response start: " + y.toString().substring(0,10));
					if ("Invalid key".equals(y.toString().trim())) {
						params.getLogger().warn("Bibliographic service not configured properly with a Zortero API key. See sysconfig.properties");
						return;
					}
					if (r2.resultCode < 0) break;
					Matcher m = java.util.regex.Pattern.compile("<div class=\"csl-entry\">.*</div>").matcher(y.toString());
					while (m.find()) {
						entries.add(m.group());
					}
					keys = new StringBuffer();
					chunkSize = 0;
				}
			}
			Collections.sort(entries);
//params.getLogger().info("bibliography: found size: "+entries.size());
			for (String e : entries) {
				z.append(e);
			}
			zFormat = "bib";
		}

		if (zFormat.equals("bib") && biblioAddJKElliot) {
			z.append("<div class=\"csl-bib-body\" style=\"line-height: 1.35; padding-left: 2em; text-indent:-2em;\"><div class=\"csl-entry\">");
			z.append("<a target=\"_blank\" href=\"/community/vmr/api/bibliography/get/index2.jsp?docID="+params.docID+"\">Lookup</a> " + doc.getGANumber() + " in J.K. Elliott's Bibliography of Greek New Testament Manuscripts at Université de Lausanne's BiBIL");
			z.append("</div></div>");
		}
		out.print(z.toString());
	}
	catch (Exception e) {}
	return;
	} while (false);
}
else ((Parameters)params).format = "html";
Serializer.reportErrors(request, response, out, params, true);
%>