package net.northking.cctp.dataPool.bus;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.dto.CpLogAddDto;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.dataPool.constants.DataPoolConstant;
import net.northking.cctp.dataPool.enums.DataPoolError;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LogRabbitMQPublisher {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HttpServletRequest request;

    public void deployLogContent(CpLogAddDto cpLogAddDto) {
        byte[] json;
        try {
            cpLogAddDto.setRemoteAddr(request.getRemoteAddr());
            json = objectMapper.writeValueAsBytes(cpLogAddDto);
        } catch (JsonProcessingException e) {
            throw new PlatformRuntimeException(DataPoolError.INSERT_LOG_FAIL);
        }
        MessageBuilder mb = MessageBuilder.withBody(json);
        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
        mb.setHeader(DataPoolConstant.CCTP_USER_ID, NKSecurityContext.getUserId());
        mb.setHeader(DataPoolConstant.SAAS_TENANT_ID, NKSecurityContext.getTenantId());
        rabbitTemplate.send(DataPoolConstant.PLATFORM_LOG_INSERT_REQ, mb.build());
    }
}
