package com.eactive.eai.common.logger;

import com.eactive.eai.common.logger.mapper.HttpAdapterExtraLogMapper;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.logger.HttpAdapterExtraLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class HttpLoggingService {

	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    
	@Autowired
    private HttpAdapterExtraLogMapper mapper;

    @Autowired
    private HttpAdapterExtraLogLogger dbLogger;

    @Autowired
    private HttpAdapterExtraLogFileLogger fileLogger;

    public void insertHttpAdapterExtraLog(HttpAdapterExtraLogVo httpAdapterExtraLogVo) throws Throwable{
        HttpAdapterExtraLog httpAdapterExtraLog = mapper.toEntity(httpAdapterExtraLogVo);
        if (EAIDBLogControl.isEnable()) {
            try {
                dbLogger.save(httpAdapterExtraLog);
                logger.debug("inserted to DB");
            } catch(Exception e){
                String message = e.getMessage();
                // 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
                // 오류 메시지 추가 - Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
                if( "ConnectionError".equals(message) || StringUtils.contains(message, "JDBCConnectionException")
                        || StringUtils.contains(message, "Unable to acquire JDBC Connection") ) {
                    EAIDBLogControl.setEnable(false);
                }
                fileLogger.writeFileLog(httpAdapterExtraLog);
                logger.debug("wrote to File");
            }
        } else {
            fileLogger.writeFileLog(httpAdapterExtraLog);
            logger.debug("wrote to File");
        }
    }
}
