package cn.reghao.tnb.search.esapp.log.mq;

import cn.reghao.jutil.jdk.web.log.AppLog;
import cn.reghao.jutil.jdk.web.log.GatewayLog;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.jutil.jdk.web.log.NginxLog;
import cn.reghao.tnb.search.esapp.log.db.AccessLogMongo;
import cn.reghao.tnb.search.esapp.log.model.po.AccessLog;
import cn.reghao.tnb.search.esapp.ws.handler.LogHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author reghao
 * @date 2024-11-28 14:37:18
 */
@Slf4j
@Component
public class RabbitListeners {
    private final LogHandler logHandler;
    private final AccessLogMongo accessLogMongo;

    public RabbitListeners(LogHandler logHandler, AccessLogMongo accessLogMongo) {
        this.logHandler = logHandler;
        this.accessLogMongo = accessLogMongo;
    }

    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(value = "tnb.log.nginx", durable = "true"),
            key = "tnb.log.nginx",
            exchange = @Exchange(value = "amq.direct"))
    )
    public void nginxLogConsumer(@Payload String msg) {
        try {
            NginxLog nginxLog = JsonConverter.jsonToObject(msg, NginxLog.class);
        } catch (Exception e) {
        }
    }

    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(value = "tnb.log.gateway", durable = "true"),
            key = "tnb.log.gateway",
            exchange = @Exchange(value = "amq.direct"))
    )
    public void gatewayLogConsumer(@Payload String msg) {
        try {
            GatewayLog gatewayLog = JsonConverter.jsonToObject(msg, GatewayLog.class);
            logHandler.pushGatewayLog(gatewayLog);
            //log.info("{} -> {}", gatewayLog.getRequestId(), gatewayLog.getRequestUrl());
            AccessLog accessLog = new AccessLog(gatewayLog);
            accessLogMongo.save(accessLog);
        } catch (Exception e) {

        }
    }

    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(value = "tnb.log.app", durable = "true"),
            key = "tnb.log.app",
            exchange = @Exchange(value = "amq.direct"))
    )
    public void appLogConsumer(@Payload String msg) {
        AppLog appLog = JsonConverter.jsonToObject(msg, AppLog.class);
        logHandler.pushAppLog(appLog);
        log.info("{}:{} -> {}", appLog.getApp(), appLog.getHost(), appLog.getMessage());
    }
}
