package com.ruoyi.system.core;

import org.springframework.stereotype.Component;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.TioConfig;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author tanyaowu
 */
@Component
public class ClientTioHandler implements ClientAioHandler {
    @Override
    public Packet heartbeatPacket(ChannelContext channelContext) {
        return null;
    }

    @Override
    public Packet decode(ByteBuffer byteBuffer, int i, int i1, int i2, ChannelContext channelContext) throws AioDecodeException {
        byte[] array = new byte[byteBuffer.remaining()];
        byteBuffer.get(array);
        MindPackage mind = new MindPackage();
        mind.setBody(array);
        return mind;
    }

    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        MindPackage helloPacket = (MindPackage) packet;
        byte[] body = helloPacket.getBody();
        int bodyLen = 0;
        if (body != null) {
            bodyLen = body.length;
        }
        ByteBuffer buffer = ByteBuffer.allocate(bodyLen);
        buffer.put(body);
        return buffer;
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        MindPackage mind = (MindPackage) packet;
        byte[] body = mind.getBody();
        String str = new String(body, StandardCharsets.UTF_8);
        System.err.println(str);
    }
}
