package com.m2pool.lease.netty.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.m2pool.lease.netty.parser.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.ArrayList;
import java.util.List;

public class MessageToJsonDecoder extends ByteToMessageDecoder {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private final List<MessageParser<?>> parsers = new ArrayList<>();

    public MessageToJsonDecoder() {
        // 初始化解析器列表
        parsers.add(new StringParser());
        parsers.add(new ClientConfigMiningParser());
        parsers.add(new GpuMessageMapParser());
        parsers.add(new ServerConfigMiningParser());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() > 0) {
            byte[] bytes = new byte[in.readableBytes()];
            in.readBytes(bytes);
            String jsonStr = new String(bytes);

            for (MessageParser<?> parser : parsers) {
                try {
                    Object message = parser.parse(objectMapper, jsonStr);
                    out.add(message);
                    return;
                } catch (Exception e) {
                    // 继续尝试下一个解析器
                }
            }
        }
    }
}
