package com.elab.spring.componts.endpoints;

import com.dianping.cat.message.io.DefaultMessageQueue;
import com.dianping.cat.message.io.TcpSocketSender;
import com.dianping.cat.message.spi.MessageTree;
import com.elab.spring.utils.SpringUtils;
import org.codehaus.plexus.PlexusContainer;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.unidal.initialization.DefaultModuleContext;
import org.unidal.initialization.ModuleContext;
import org.unidal.lookup.ContainerLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

/**
 * Cat排查端点暴露
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/6 - 13:45
 */
@Endpoint(id = "cat")
public class CatEndpoint {

    @ReadOperation
    public Object analyseLocalQueue() {
        PlexusContainer container = ContainerLoader.getDefaultContainer();
        ModuleContext ctx = new DefaultModuleContext(container);
        TcpSocketSender tcpSocketSender = ctx.lookup(TcpSocketSender.class);
        DefaultMessageQueue atomicQueue =
            SpringUtils.getFieldObjectValue(tcpSocketSender.getClass(), "m_atomicQueue", DefaultMessageQueue.class);

        BlockingQueue m_queue = SpringUtils.getFieldObjectValue(atomicQueue.getClass(), "m_queue", BlockingQueue.class);

        List<MessageTree> messageTrees = new ArrayList<>();

        m_queue.drainTo(messageTrees);
        // todo 未完成，目的是希望在队列满了的时候，分析队列中到底是哪些埋点造成的。
        Map<String, Map<String, Object>> resultMap = new HashMap<>();

        return null;
        //        messageTrees.forEach((tree) -> {
        //            String type = tree.getMessage().getType();
        //            String name = tree.getMessage().getName();
        //            String key = type + "-" + name;
        //            Map<String, Object> map = resultMap.computeIfAbsent(key, k -> new HashMap<>());
        //
        //        });
    }

}
