/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.common.log;

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.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

/**
 * Http日志生产者
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
@Component
@RefreshScope
public class HttpLogRabbitMQProducer implements HttpLogProducer
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(HttpLogRabbitMQProducer.class);

  /**
   * 微服务名称
   */
  @Value("${spring.application.name}")
  private String appName;

  /**
   * 当前节点的IP地址
   */
  @Value("${spring.cloud.client.ip-address}")
  private String host;

  /**
   * 当前节点的端口
   */
  @Value("${server.port}")
  private int port;

  @Value("${nk.httpLog:false}")
  private boolean useHttpLog;

  private final RabbitTemplate rabbitTemplate;

  private final ObjectMapper objectMapper;

  public HttpLogRabbitMQProducer(RabbitTemplate rabbitTemplate, ObjectMapper objectMapper)
  {
    this.rabbitTemplate = rabbitTemplate;
    this.objectMapper = objectMapper;
  }

  @Override
  public void process(HttpLog httpLog)
  {
    long endTime = System.currentTimeMillis();
    httpLog.setAppName(appName);
    httpLog.setHost(host);
    httpLog.setPort(port);
    httpLog.setEndTime(endTime);
    httpLog.setElapsedTime(endTime - httpLog.getStartTime());

    try
    {
      byte[] json = objectMapper.writeValueAsBytes(httpLog);
      MessageBuilder mb = MessageBuilder.withBody(json);
      mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
      if (useHttpLog)
      {
        rabbitTemplate.send("CCTP.OPERATE.LOG", mb.build());
      }
    } catch (JsonProcessingException e)
    {
      logger.error("", e);
    }
  }

}
