import java.net.URLDecoder;
import java.util.Calendar;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AuthMng {
	
	/**
	 * Generates authenticated URL string for media access
	 * @param objid Object ID of device
	 * @param archive TRUE if stream is archive
	 * @param startTime Start of the archive segment (in milliseconds since Epoch)
	 * @param endTime End of the archive segment (in milliseconds since Epoch)
	 * @param analytics 
	 * @return The rtsp url
	 * @throws Exception On failure to get media access authorization
	 */
	public static String getMediaURL(int objid, boolean archive, long startTime, long endTime, boolean analytics) throws Exception {
		Calendar utcCalendar = Calendar.getInstance();
		// request media URL and authorization ticket
		//
		String apiCallPath = "/api/authmng.php?return=mediastreamauth&objid="
				+ objid;
		if (analytics){
			apiCallPath += "&analytics=3";
		}
		
		if (archive) {
			apiCallPath += "&streamtype=archive";

			
			utcCalendar.setTimeInMillis(startTime);
			apiCallPath += String.format(
					"&time_start=%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS",
					utcCalendar);

			utcCalendar.setTimeInMillis(endTime);
			apiCallPath += String.format(
					"&time_end=%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS",
					utcCalendar);
		} else {
			apiCallPath += "&streamtype=live";
		}

		AppContext context = AppContext.getInstance();
		Document doc = context.getAPICallDocument(apiCallPath);

		NodeList nl = doc.getDocumentElement().getElementsByTagName(
				"AUTHORIZATION");
		if (nl == null || nl.getLength() < 1) {
			throw new Exception("Failed to get media access authorization");
		} else {
			// assemble media URL
			//
			Element authElement = (Element) nl.item(0);
			String mediaURL = URLDecoder.decode(
					authElement.getAttribute("URL"), "UTF-8");
			mediaURL += "&authorizationid=" + authElement.getAttribute("ID");
			System.out.println("MediaUrl : " + mediaURL);
			return mediaURL;
		}
	}
}