package com.njzscloud.common.localizer.jt808.message;

import cn.hutool.core.util.CharsetUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.localizer.contant.BodyCharset;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.Getter;
import lombok.experimental.Accessors;

/**
 * 终端文本消息
 */
@Accessors(chain = true)
public class TerminalTxtMessage {
    /**
     * 编码类型
     */
    @Getter
    private final byte type;
    /**
     * 文本信息
     */
    private final byte[] txt;

    public TerminalTxtMessage(ByteBuf body) {
        this.type = body.readByte();
        this.txt = ByteBufUtil.getBytes(body);
    }

    public String getTxt() {
        return new String(txt, this.type == 0x00 ?
                CharsetUtil.CHARSET_GBK :
                CharsetUtil.CHARSET_UTF_8);
    }

    public String getTxt(BodyCharset charset) {
        switch (charset) {
            case GBK:
                return new String(txt, CharsetUtil.CHARSET_GBK);
            case ASCII:
                StringBuilder stringBuilder = new StringBuilder();
                for (byte b : txt) {
                    stringBuilder.append((char) b);
                }
                return stringBuilder.toString();
            default:
                throw Exceptions.error("不支持的文本消息编码：{}", charset);
        }
    }
}
