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

import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.localizer.contant.BodyCharset;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

@Getter
@Setter
@ToString
@Slf4j
@Accessors(chain = true)
public class ServerTxtMessage implements ServerMessageBody {
    /**
     * 文本消息标志位，
     * 途强：0x01 表示紧急文本消息
     * 紫金航天：0x01表示后续数据是指令
     */
    private byte flag;
    /**
     * 文本消息内容
     */
    private String txt;

    /**
     * 文本消息编码，默认UTF-8
     */
    private BodyCharset charset;

    public ServerTxtMessage(String txt) {
        this(txt, BodyCharset.GBK);
    }

    public ServerTxtMessage(String txt, BodyCharset charset) {
        this.flag = 0x01;
        this.txt = txt;
        this.charset = charset;
    }

    public byte[] toBytes() {
        byte[] messageBody = new byte[txt.length() + 1];
        messageBody[0] = flag;
        switch (charset) {
            case ASCII: {
                for (int i = 0; i < txt.length(); i++) {
                    char c = txt.charAt(i);
                    messageBody[i + 1] = (byte) c;
                }
            }
            break;
            case GBK: {
                try {
                    System.arraycopy(txt.getBytes(), 0, messageBody, 1, txt.length());
                } catch (Exception e) {
                    throw Exceptions.error(e, "文本消息构建失败，原文本：{}", txt);
                }
            }
            break;
            default: {
                throw Exceptions.error("不支持的文本消息编码：{}", charset);
            }
        }

        return messageBody;
    }
}
