package com.eactive.eai.adapter.http.dynamic;

import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.InboundErrorLogger;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.UUIDGenerator;
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@SuppressWarnings("serial")
public class RestApiAdapterMain extends HttpServlet implements HttpAdapterServiceKey {
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	public void init() {
	}

	public void service(HttpServletRequest request, HttpServletResponse response) {
		HttpDynamicInAdapterManager manager = HttpDynamicInAdapterManager.getInstance();
		// /ONLWeb/api/v1/public/getUserInfo.svc
		String apiUri = request.getRequestURI();
		// /api/v1/public/getUserInfo.svc
		apiUri = StringUtils.removeStart(apiUri, request.getContextPath());
		apiUri = StringUtils.removeEnd(apiUri, "/");
		HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, manager);

		if (logger.isDebug()) {
			logger.debug("HttpDynamicInAdapter] service request uri : " + request.getRequestURI());
		}

		if (adptUri == null) {
			logError(request, response);
			return;
		}
		HttpAdapterService service = HttpAdapterServiceFactory.createFactory(adptUri.getAdptType());
		service.service(adptUri.getAdptGrpName(), adptUri.getAdptName(), request, response);
	}

	/**
	 * url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
	 * /api/v1/public/getUserInfo.svc
	 * 
	 * @param apiUri
	 * @return
	 */
	private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager) {
		if (StringUtils.isBlank(apiUri)) {
			return null;
		}

		for (int i = 0; i < 10; i++) {
			HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
			if (adptUri != null) {
				return adptUri;
			}
			
			// /api/v1/public
			apiUri = StringUtils.substringBeforeLast(apiUri, "/");
			if (apiUri.length() < 4) { // /api
				return null;
			}
		}

		return null;
	}

	private void logError(HttpServletRequest request, HttpServletResponse response) {
		InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();

		EAIServerManager eaiServerManager = EAIServerManager.getInstance();
		String serverName = eaiServerManager.getLocalServerName();
		String uuid = null;
		StringBuffer sb = new StringBuffer();

		String instanceid1 = serverName.substring(0, 2);
		String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
		String instid = instanceid1 + instanceid2;
		uuid = instid + UUIDGenerator.getUUID();

		String[] msgArgs = new String[1];
		msgArgs[0] = request.getRequestURI();

		String errorCode = "RECEAIIRP010";
		String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);

		errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
		errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
		errorInfoVO.setErrCd(errorCode); // 에러코드
		errorInfoVO.setErrTxt(errorMsg); // 에러내용
		errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
		errorInfoVO.setErrDstcd(" ");
		sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
				.append(request.getRequestURI());
		errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
		errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명

		InboundErrorLogger.error(errorInfoVO);

		response.setStatus(404);
		try {
			response.getWriter().println("can not find uri '" + request.getRequestURI() + "'");
		} catch (Exception ex) {
			// IGNORE
		}
	}
}
