package net.northking.cctp.platform.bus.notice;

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.platform.bus.BusConstants;
import net.northking.cctp.platform.constants.PlatformAppError;
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 implements LogPublisher {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public void sendLog(CpLogAddDto cpLogAddDto) {
        byte[] json;
        try {
            cpLogAddDto.setRemoteAddr(request.getRemoteAddr());
            json = objectMapper.writeValueAsBytes(cpLogAddDto);
        } catch (JsonProcessingException e) {
            throw new PlatformRuntimeException(PlatformAppError.NOTICE_INSERT);
        }
        MessageBuilder mb = MessageBuilder.withBody(json);
        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
        mb.setHeader(BusConstants.Key_CCTP_User_ID, NKSecurityContext.getUserId());
        mb.setHeader(BusConstants.Key_SaaS_Tenant_ID, NKSecurityContext.getTenantId());
        rabbitTemplate.send(BusConstants.Q_Platform_Log_Insert_REQ, mb.build());
    }
}
