package com.eactive.eai.adapter;

import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.http.HttpStatusException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class ElinkDefaultAdapter implements ElinkAdapter {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private AdapterManager manager;

	public ElinkDefaultAdapter() {
		this.manager = AdapterManager.getInstance();
	}

	public Object callService(String adapterGroupName, Properties prop, Object message, Properties tempProp)
			throws Exception {
		String adapterName = tempProp.getProperty(com.eactive.eai.adapter.Keys.OUT_ADAPTER_NAME);
		AdapterGroupVO group = this.manager.getAdapterGroupVO(adapterGroupName);
		if (group == null) {
			String code = "RECEAIAAC027";
			String[] msgArgs = new String[1];
			msgArgs[0] = adapterGroupName;
			String errText = ExceptionUtil.make(code, msgArgs);
			if (logger.isError())
				logger.error(errText);
			throw new Exception(errText);
		}
		
		AdapterVO adapterVO = null;
		if(StringUtils.isNotEmpty(adapterName)) {
			adapterVO = group.getAdapterVO(adapterName);
		}
		
		group.increase();
		
		tempProp.setProperty(com.eactive.eai.adapter.Keys.OUT_ADAPTER_GROUP_NAME, adapterGroupName);
		// set AdapterGroup charset
		tempProp.setProperty(com.eactive.eai.adapter.Keys.CHARSET_KEY_OUT,
				StringUtils.defaultIfBlank(group.getMessageEncode(), Charset.defaultCharset().name()));

		try {
			if(adapterVO != null) adapterVO.incrementRequestCount();
			return execute(prop, message, tempProp);
		} catch (SocketTimeoutException ste) {
			throw ste;
		} catch (HttpStatusException hse) {
			throw hse;
		} catch (Exception e) {
			throw e;
		} finally {
			group.decrease();
			if(adapterVO != null) adapterVO.decrementRequestCount();
		}
	}

	public Object execute(Properties prop, Object message, Properties tempProp) throws Exception {
		throw new java.lang.UnsupportedOperationException("RECEAIAAC029");
	}
}
