package org.ecoinformatics.ecogrid.lsid;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import com.ibm.lsid.LSID;
import com.ibm.lsid.ExpiringResponse;
import com.ibm.lsid.wsdl.LSIDDataPort;
import com.ibm.lsid.wsdl.LSIDMetadataPort;

import com.ibm.lsid.wsdl.SOAPLocation;
import com.ibm.lsid.wsdl.HTTPLocation;

import com.ibm.lsid.server.LSIDServerException;
import com.ibm.lsid.server.LSIDServiceConfig;

import com.ibm.lsid.server.impl.SimpleAuthority;

public class LSIDAuthorityMain extends SimpleAuthority {

	private LSIDDataLookup lookup = null;

	public void initService(LSIDServiceConfig cf) throws LSIDServerException {
        System.out.println("Starting LSIDAuthorityMain (Metacat).");
		lookup = new LSIDDataLookup();
	}

	public ExpiringResponse getKnownURIs() throws LSIDServerException {
		return null;
	}

	public LSIDMetadataPort[] getMetadataLocations(LSID lsid, String url) {
		if (lookup == null)
			return null;

		int lsType;
		try {
			lsType = lookup.lsidType(lsid);
		}
		catch (LSIDServerException ex) {
			ex.printStackTrace();
			lsType = LSIDDataLookup.UNKNOWN;
		}
		if (lsType == LSIDDataLookup.UNKNOWN)
			return null;

		HostDescriptor hd = new HostDescriptor(url);
		return new LSIDMetadataPort[] {
		// thau added http metadata port here
			new HTTPLocation(
				hd.host, hd.port,
				hd.pathPrefix + "/authority/metadata" 
			),
		new SOAPLocation(
				hd.baseURL + "metadata"
			)
		};
	}

	public LSIDDataPort[] getDataLocations(LSID lsid, String url) {
		if (lookup == null)
			return null;

		int lsType;
		try {
			lsType = lookup.lsidType(lsid);
		}
		catch (LSIDServerException ex) {
			ex.printStackTrace();
			lsType = LSIDDataLookup.UNKNOWN;
		}
		if (lsType == LSIDDataLookup.UNKNOWN)
			return null;
		if (lsType == LSIDDataLookup.ABSTRACT)
			return new LSIDDataPort[0];
		
		HostDescriptor hd = new HostDescriptor(url);
		return new LSIDDataPort[] {
			new HTTPLocation(
				hd.host, hd.port,
				hd.pathPrefix + "/authority/data"
			),
			new SOAPLocation(
				hd.baseURL + "data"
			)
		};
	}

	private static final Pattern HOST_PTN = Pattern.compile(
		"https?://([^/:]+)(?::(\\d+))?(.*)/authority(.*)"
	);
	
	/* Q&D implementation */
	private class HostDescriptor {
		public String host;
		public int port;
		public String pathPrefix;
		public String baseURL;
		
		public HostDescriptor(String url) {
			host = "localhost";
			port = -1;
			pathPrefix = "";
			if (url != null || url.length() > 0) {
				Matcher m = HOST_PTN.matcher(url);
				if (m.lookingAt()) {
					host = m.group(1);
					if ((m.group(2) != null) && (m.group(2).length() > 0))
						port = Integer.parseInt(m.group(2));
					pathPrefix = m.group(3);
				}
			}
			if (port > 0)
				baseURL = "http://" + host + ":" + port +
					pathPrefix + "/authority/";
			else
				baseURL = "http://" + host + pathPrefix + "/authority/";
		}
	}
}
