package com.njzscloud.common.redis.support;

import com.njzscloud.common.core.fastjson.Fastjson;
import io.lettuce.core.codec.RedisCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

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

/**
 * Redis 序列化/反序列化 器（采用 Fastjson，已开启自动类型处理）
 */
public class RedisFastjsonCodec implements RedisCodec<String, Object> {
    private static final byte[] EMPTY = new byte[0];

    @Override
    public String decodeKey(ByteBuffer bytes) {
        return Unpooled.wrappedBuffer(bytes).toString(StandardCharsets.UTF_8);
    }

    @Override
    public Object decodeValue(ByteBuffer bytes) {
        String jsonStr = Unpooled.wrappedBuffer(bytes).toString(StandardCharsets.UTF_8);
        return Fastjson.toBean(jsonStr, Object.class);
    }

    @Override
    public ByteBuffer encodeKey(String key) {
        if (key == null) {
            return ByteBuffer.wrap(EMPTY);
        }
        int utf8MaxBytes = ByteBufUtil.utf8MaxBytes(key);

        ByteBuffer buffer = ByteBuffer.allocate(utf8MaxBytes);

        ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer);
        byteBuf.clear();
        ByteBufUtil.writeUtf8(byteBuf, key);
        buffer.limit(byteBuf.writerIndex());

        return buffer;
    }

    @Override
    public ByteBuffer encodeValue(Object value) {
        String jsonStr = Fastjson.toJsonStr(value);
        if (jsonStr == null) {
            return ByteBuffer.wrap(EMPTY);
        }
        int utf8MaxBytes = ByteBufUtil.utf8MaxBytes(jsonStr);

        ByteBuffer buffer = ByteBuffer.allocate(utf8MaxBytes);

        ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer);
        byteBuf.clear();
        ByteBufUtil.writeUtf8(byteBuf, jsonStr);
        buffer.limit(byteBuf.writerIndex());

        return buffer;
    }
}
