package net.northking.cctp.upperComputer.driver.agent.command.protocol;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;

public class ProtocolStreamUtil {

    /**
     * 发送文本<br>
     * 作为DataOutput方法的补充<br>
     * 文本字节长度+文本字节
     *
     * @param output 发送操作对象
     * @param text   要发送的文本内容
     * @throws IOException 发送过程中发生输入输出错误
     */
    public static void writeText(DataOutput output, String text) throws IOException {
        byte[] textByteArray = text.getBytes();
        output.writeInt(textByteArray.length);
        output.write(textByteArray);
    }

    /**
     * 读取文本<br>
     * 作为DataInput方法的补充<br>
     * 会读取一个整型作为接下来要读取的文本字节长度
     *
     * @param input 读取操作对象
     * @return 读取到的文本
     * @throws IOException 读取过程中发生输入输出错误
     */
    public static String readText(DataInput input) throws IOException {
        int textLength = input.readInt();
        byte[] textByteArray = new byte[textLength];
        input.readFully(textByteArray);
        return new String(textByteArray);
    }

    public static int[] readIntArray(DataInput input) throws IOException {
        int length = input.readInt();
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            array[i] = input.readInt();
        }
        return array;
    }

    public static <K> void writeNullable(DataOutput output, K data, WriteNullableData<K> writer) throws IOException {
        if (data == null) {
            output.writeBoolean(false);
        } else {
            output.writeBoolean(true);
            writer.write(output, data);
        }
    }

    public static <K> K readNullable(DataInput input, ReadNullableData<K> reader) throws IOException {
        if (input.readBoolean()) {
            return reader.read(input);
        }
        return null;
    }

    public static ArrayList<String> readStringArrayList(DataInput input) throws IOException {
        int length = input.readInt();
        ArrayList<String> list = new ArrayList<String>(length);
        for (int i = 0; i < length; i++) {
            list.add(readText(input));
        }
        return list;
    }

    public interface ReadNullableData<K> {
        K read(DataInput input) throws IOException;
    }

    public interface WriteNullableData<K> {
        void write(DataOutput output, K data) throws IOException;
    }
}
