package net.northking.cctp.scriptcase.bus;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.scriptcase.dto.app.AppDeleteDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
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 org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class AppRabbitMQPublisher {

    private static final String queueName = "Mobile.App.Delete.REQ";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HttpServletRequest request;

    public void sendDeleteAppInfo(AppDeleteDto data){
        //如果队列不存在就创建
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        if (!ObjectUtils.isEmpty(rabbitAdmin.getQueueProperties(queueName))) {
            byte[] json;
            try {
                json = objectMapper.writeValueAsBytes(data);
            } catch (JsonProcessingException e) {
                throw new PlatformRuntimeException(new ErrorMessage("App删除信息实体转换失败"));
            }
            MessageBuilder mb = MessageBuilder.withBody(json);
            mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
            mb.setHeader("CCTP_User_ID", NKSecurityContext.getUserId());
            mb.setHeader("SaaS_Tenant_ID", NKSecurityContext.getTenantId());
            rabbitTemplate.send("Mobile.App.Delete.REQ", mb.build());
        }else {
            rabbitAdmin.declareQueue(new Queue(queueName));
        }
    }



}
