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 io.undertow.servlet.handlers.DefaultServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class HttpAdapterCustom extends DefaultServlet implements HttpAdapterServiceKey {
	
	private static final long serialVersionUID = 1L;

	// Adapter Logger
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpDynamicPortInAdapterManager manager = HttpDynamicPortInAdapterManager.getInstance();
		Integer localPort = request.getLocalPort();
		String requestUrl = request.getRequestURI(); // /api/v1/public/getUserInfo.svc

		HttpDynamicInAdapterUri adptUri = findAdptUri(localPort, requestUrl, manager);

		if (logger.isDebug()) {
			logger.debug("[HttpAdapterCustom] request adapter info : " + adptUri);
		}

		if (adptUri == null) {
			logError(request, response, null);
			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(Integer localPort, String apiUri,
			HttpDynamicPortInAdapterManager manager) {
		apiUri = StringUtils.removeEnd(apiUri, "/");
		if (StringUtils.isBlank(apiUri)) {
			return null;
		}

		HttpDynamicInAdapterUri adptUri = null;
		for (int i = 0; i < 10; i++) {
			adptUri = manager.getAdptUri(localPort, apiUri);
			if (adptUri != null) {
				return adptUri;
			}

			// /api/v1/public
			apiUri = StringUtils.substringBeforeLast(apiUri, "/");
			if (StringUtils.isBlank(apiUri)) {
				return manager.getAdptUri(localPort, "/");
			}
		}

		return null;
	}

    private void logError(HttpServletRequest request, HttpServletResponse response, String msg) {
    	
		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 = null;
        if (msg == null) {
        	errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
        } else {
        	errorMsg = ExceptionUtil.make(new Exception(msg),  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 {
        	if (msg == null) {
        		response.getWriter().println("can not find uri '"+request.getRequestURI()+"'");
        	} else {
        		response.getWriter().println(msg);
        	}
        } catch (Exception ex) {
            // IGNORE
        }
		
    }
}
