package com.eactive.eai.custom.pretty;

import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageManager;
import com.eactive.eai.common.message.ServiceMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformManager;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class PrettyPrintController {
    public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    private static final String FALLBACK_ERROR_JSON = "{ \"error\": true, \"result\": \"occur error building responseMessage.\" }";

    @RequestMapping(value = "/PrettyPrint", method = RequestMethod.POST, consumes = "application/json", produces = "application/json; charset=UTF-8")
    @ResponseBody
    public ResponseEntity<String> tokenJson(@RequestBody PrettyPrintRequest transFormRequest,
	    HttpServletRequest request, HttpServletResponse response) {

	PrettyPrintResponse prettyPrintResponse = new PrettyPrintResponse();

	try {

	    String layoutName = getLayoutName(transFormRequest);

	    String result = Optional.ofNullable(MessageFactory.getFactory().getMessage(layoutName)).map(message -> {

		message.setData(transFormRequest.getBizData());

		return message.toXMLString();
	    }).orElseThrow(() -> new IllegalArgumentException("업무 메세지 파싱중 오류"));

	    prettyPrintResponse.setResult(result);
	    String successJson = buildResponseMessage(prettyPrintResponse);
	    return ResponseEntity.ok(successJson);
	} catch (IllegalArgumentException e) {
	    logger.error("Pretty print 실패", e);
	    prettyPrintResponse.setError(true);
	    prettyPrintResponse.setResult("잘못된 업무데이터 전문 파싱 중 에러");
	    String errorJson = buildResponseMessage(prettyPrintResponse);
	    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorJson);
	} catch (Exception e) {
	    logger.error("Pretty print 실패", e);
	    prettyPrintResponse.setError(true);
	    prettyPrintResponse.setResult("업무전문 파싱에 필요한 layout정보 가져오는 중 실패");
	    String errorJson = buildResponseMessage(prettyPrintResponse);
	    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorJson);
	}

    }

    String buildResponseMessage(PrettyPrintResponse prettyPrintResponse) {
	try {
	    ObjectMapper mapper = new ObjectMapper();
	    return mapper.writeValueAsString(prettyPrintResponse);
	} catch (Exception e) {
	    logger.error("occur error building responseMessage.", e);
	    return FALLBACK_ERROR_JSON;
	}

    }

    private String getLayoutName(PrettyPrintRequest request) throws Exception {

	EAIMessageManager eaiMessageManager = EAIMessageManager.getInstance();

	EAIMessage eaiMessage = eaiMessageManager.getEAIMessage(request.getIntrefaceId());

	TransformManager transformManager = TransformManager.getManager();

	if (eaiMessage == null) {

	    throw new IllegalArgumentException("Invalid interfaceId=" + request.getIntrefaceId());

	}

	List<ServiceMessage> serviceMessageList = eaiMessage.getSvcMsgs();

	ServiceMessage serviceMessage = serviceMessageList.get(0);

	String transformId;
	Transform transformInfo;
	Layout layout;

	switch (request.getLogProcessNo()) {
	case "100":
	    transformId = serviceMessage.getCnvMsgID();
	    transformInfo = transformManager.getTransform(transformId);
	    layout = transformInfo.getSourceLayout(0);
	    return layout.getName();
	case "200":
	    transformId = serviceMessage.getCnvMsgID();
	    transformInfo = transformManager.getTransform(transformId);
	    layout = transformInfo.getTargetLayout();
	    return layout.getName();
	case "300":
	    transformId = request.isError() ? serviceMessage.getErrRspCnvMsgID() : serviceMessage.getBsRspCnvMsgID();
	    transformInfo = transformManager.getTransform(transformId);
	    layout = transformInfo.getSourceLayout(0);
	    return layout.getName();
	case "400":
	    transformId = request.isError() ? serviceMessage.getErrRspCnvMsgID() : serviceMessage.getBsRspCnvMsgID();
	    transformInfo = transformManager.getTransform(transformId);
	    layout = transformInfo.getTargetLayout();
	    return layout.getName();
	default:
	    throw new IllegalArgumentException("Invalid logProcessNo: " + request.getLogProcessNo());
	}

    }

}
