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.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class HttpAdapterMain extends HttpServlet implements HttpAdapterServiceKey {
	public void init() {
	}

	public void service(HttpServletRequest request, HttpServletResponse response) {
		Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
		HttpDynamicInAdapterManager manager = HttpDynamicInAdapterManager.getInstance();
		String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");// context path 제거

		String customUri = getCustomUri(orgUri, 3); // adapter name 이후 제거
		HttpDynamicInAdapterUri adptUri = manager.getAdptUri(customUri);

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

		if (adptUri == null) {
			logError(request, response);
			return;
		}
		
		// rest일때만 하위 uri 허용
		if (!orgUri.equals(customUri) && !HttpAdapterServiceType.REST.toString().equals(adptUri.getAdptType())) { 
			logError(request, response);
			return;
		}
		
		HttpAdapterService service = HttpAdapterServiceFactory.createFactory(adptUri.getAdptType());
		if (service == null) {
			logger.debug("HttpDynamicInAdapter] HttpAdapterService create Error : " + adptUri.getAdptType());
			logError(request, response);
		} else {
			service.service(adptUri.getAdptGrpName(), adptUri.getAdptName(), request, response);
		}
	}

	private void logError(HttpServletRequest request, HttpServletResponse response) {
		Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
		InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();

		EAIServerManager eaiServerManager = EAIServerManager.getInstance();

		String serverName = eaiServerManager.getLocalServerName();
		String uuid = null;
		StringBuffer sb = new StringBuffer();
//        
//        String instanceid1 = "";
//        String instanceid2 = "";
//        if(serverName != null) {
//			//juns 서버명 변경에 따른 인스턴스 룰 추출변경 
//	        //ex)EAIDSG_i11 => EAIDS01_i01  결과 EA11
//	        instanceid1 = serverName.substring(0,2);
//	//        String instanceid2 = serverName.substring(serverName.length()-2, serverName.length());
//			instanceid2 = serverName.substring(serverName.length()-5, serverName.length()-4)
//					           + serverName.substring(serverName.length()-1, serverName.length());
//        }
		String instid = eaiServerManager.getGroupInstId();
		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) {
			logger.error("write error", ex);
		}

	}
//	   public static void main(String args[]) throws Exception {
//	   test();
//}

// private static void test() throws Exception {
//    	String orgUri = "/HTT/CbsInHttpSys/ABC/DEF";
////    	System.out.println(getCustomUri(orgUri,3));
//
//    }
	public static String getCustomUri(String url, int length) {
		// return
		// Stream.of(url.split("/")).limit(length).collect(Collectors.joining("/")) ;
		String[] urls = url.split("/");
		List<String> newUrls = new ArrayList<>();
		Collections.addAll(newUrls, urls);
		return StringUtils.join(newUrls.subList(0, length).toArray(), "/");
	}
}
