package net.northking.cctp.common.s3;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.MediaType;

/**
 * 推送附件消息生产者的实现类
 */
public class AttachMQProducer implements AttachmentProducer
{
  private static final Logger logger = LoggerFactory.getLogger(AttachMQProducer.class);

  private final RabbitTemplate rabbitTemplate;

  private ObjectMapper objectMapper;

  public AttachMQProducer(RabbitTemplate rabbitTemplate)
  {
    objectMapper = new ObjectMapper();
    this.rabbitTemplate = rabbitTemplate;
  }

  @Override
  public void process(NKFile nkFile)
  {
    try
    {
      byte[] json = objectMapper.writeValueAsBytes(nkFile);
      MessageBuilder mb = MessageBuilder.withBody(json);
      mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
      rabbitTemplate.send(RoutingKey, mb.build());
    } catch (JsonProcessingException e)
    {
      logger.error("JSON序列化异常", e);
    }
  }

  @Override
  public void delete(String tenantId, String fileId)
  {
    NKFile nkFile = new S3File();
    nkFile.setTenantId(tenantId);
    nkFile.setId(fileId);
    nkFile.setDeleted(true);
    nkFile.setCreatedTime(null); // 避免创建时间更新
    logger.info("发送删除文件消息：{}", JSON.toJSONString(nkFile));
    process(nkFile);
  }
}
