package com.eactive.eai.adapter.app;

import com.eactive.eai.adapter.ElinkDefaultAdapter;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.common.util.Logger;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.util.Properties;

public class BusinessApplicationAdapter extends ElinkDefaultAdapter {
	public static final String ADAPTER_PROP_CLASS_NAME = "BUSINESS_CLASS_NAME";
	public static final String REST_OPTION_CLASS_NAME = "businessClassName";

	@Override
	public Object execute(Properties prop, Object message, Properties tempProp) throws Exception {
		String restOption = prop.getProperty(HttpClientAdapterServiceKey.REST_OPTION);
		JSONObject restOptionObject = parseJson(restOption);

		String businessClassName = null;
		if (restOptionObject != null) {
			businessClassName = (String) restOptionObject.get(REST_OPTION_CLASS_NAME);
		}

		if (StringUtils.isBlank(businessClassName)) {
			businessClassName = prop.getProperty(ADAPTER_PROP_CLASS_NAME);
			if (StringUtils.isBlank(businessClassName)) {
				throw new Exception(ADAPTER_PROP_CLASS_NAME + " is not set.");
			}
		}

		BusinessApplication app = BusinessApplicationFactory.createApplication(businessClassName);
		return app.executeApplication(prop, message, tempProp);
	}

	@SuppressWarnings("deprecation")
	private JSONObject parseJson(String message) {
		if (StringUtils.isBlank(message)) {
			return null;
		}

		return (JSONObject) JSONValue.parse(message);
	}
}
