package net.northking.cctp.upperComputer.driver.ios.packet;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.nio.ByteBuffer;


public class CommandPacket implements ICommandPacket {

    private final Logger logger = LoggerFactory.getLogger(CommandPacket.class);

    private final int commandId;

    private int requestId = 0;

    private byte[] carryingData = new byte[0];

    public CommandPacket(int commandId) {
        this.commandId = commandId;
    }

    @Override
    public int commandId() {
        return commandId;
    }

    @Override
    public int getRequestId() {
        return requestId;
    }

    @Override
    public void setRequestId(int id) {
        if (requestId != 0) throw new IllegalStateException("请求ID已经设置，不应修改");
        requestId = id;
    }

    @Override
    public byte[] getCarryingData() {
        return carryingData;
    }

    @Override
    public void setCarryingData(byte[] data) {
        if (data == null) throw new IllegalArgumentException("携带的数据不应为null，请使用new byte[0]");
        this.carryingData = data;
    }

    @Override
    public ICommandPacket createResponse(byte[] carryingData) {
        CommandPacket packet = new CommandPacket(commandId);
        packet.setRequestId(requestId);
        packet.carryingData = carryingData;
        return packet;
    }

    @Override
    public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + carryingData.length);
        buffer.putInt(commandId());
        buffer.putInt(requestId);
        buffer.putInt(carryingData.length);
        if (carryingData.length > 0) {
            buffer.put(carryingData);
        }
        return buffer.array();
    }

    @Override
    public <T extends ICommandData> boolean fillICommandData(T commandData) {
        try {
            commandData.buildFromInput(new DataInputStream(new ByteArrayInputStream(carryingData)));
        } catch (Exception e) {
            logger.error("填充对象" + commandData.getClass().getSimpleName() + "时发生异常", e);
            return false;
        }
        return true;
    }
}
