package nc.pub.framework.client.dispatch;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.framework.core.common.IConfigMetaService;
import nc.bs.framework.rmi.Address;
import nc.bs.framework.rmi.RemoteContextStub;
import nc.bs.logging.Logger;
import nc.pub.framework.client.dispatch.itf.IClientDispatchService;
import nc.vo.jcom.lang.StringUtil;

public class ClientDispatchCfgUtil {

	// Map<Service-Group>
	private static ClientDispatchCfg clientDispatchCfg = null;
	private static boolean hasInit = false;

	public static void init(RemoteContextStub remoteContextStub) {
		if (!hasInit) {
			initConfig(remoteContextStub);
		}
	}

	/**
	 * // client 不需要同步
	 * 
	 * @param remoteContextStub
	 */
	private static void initConfig(RemoteContextStub remoteContextStub) {
		try {
			IClientDispatchService srv = (IClientDispatchService) remoteContextStub.lookup("nc.pub.framework.client.dispatch.itf.IClientDispatchService");
			clientDispatchCfg = srv.getClientDispatchConfig();
			hasInit = true;
		} catch (Exception e) {// 防止master不通，导致失败
			Logger.error("init clientDsiapConfig error!!", e);
			hasInit = false;
		}

	}

	/**
	 * * URI
	 * 
	 * @param serviceName
	 * @return
	 */

	public static String getGroup(String serviceName) {
		if (!RuntimeEnv.getInstance().isRunningInServer()) {
			if (clientDispatchCfg == null) {
				return "";
			}
			String busiAction = InvocationInfoProxy.getInstance().getBusiAction();
			return clientDispatchCfg.getURIGroup(busiAction, serviceName);
		}
		return "";
	}

	public static String getURL(String serviceName, Address dispatchUrl) {
		String path = "";
		if (!RuntimeEnv.getInstance().isRunningInServer()) {
			if (clientDispatchCfg == null) {
				return "";
			}
			String busiAction = InvocationInfoProxy.getInstance().getBusiAction();
			path = clientDispatchCfg.getURL(busiAction, serviceName);
			if (!StringUtil.isEmptyWithTrim(path)) {
				if (path.contains("*:")) {
					String port = path.substring(path.indexOf("*:") + "*:".length());
					port = dealTag(port);
					path = dispatchUrl.getProtocol() + "://" + dispatchUrl.getHost() + ":" + port + dispatchUrl.getPath();
				} else {
					path = dealTag(path);
					path = path + dispatchUrl.getPath();
				}
			}
		}
		return path;
	}

	private static String dealTag(String path) {
		if (path.endsWith("/")) {
			path = path.substring(0, path.length() - 1);
		}
		return path;
	}

	/** lmc config使用 **/
	public static ClientDispatchCfg getCurConfig() {
		return clientDispatchCfg;
	}

	public static void setCurConfig(ClientDispatchCfg cdf) {
		clientDispatchCfg = cdf;
	}

}
