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


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

/**
 * 异步指令数据包监听器
 */
public class AsyncPacketListener implements PacketHandler {

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

    private final int commandId;

    private final int requestId;

    private final PacketHandler handler;

    public AsyncPacketListener(int commandId) {
        this.commandId = commandId;
        this.requestId = 0;
        this.handler = this;
    }

    public AsyncPacketListener(int commandId, PacketHandler handler) {
        this.commandId = commandId;
        this.requestId = 0;
        this.handler = handler;
    }

    public AsyncPacketListener(int commandId, int requestId, PacketHandler handler) {
        this.commandId = commandId;
        this.requestId = requestId;
        this.handler = handler;
    }

    public int getCommandId() {
        return commandId;
    }

    public int getRequestId() {
        return requestId;
    }

    public boolean tryHandle(PacketTransfer transfer, ICommandPacket packet) {
        boolean result = packet.commandId() == commandId && requestId == packet.getRequestId();
        if (result) {
            try {
                handler.handle(transfer, packet);
            } catch (Exception e) {
                logger.error("指令处理器处理指令数据时发生异常", e);
            }
        }

        return result;
    }

    @Override
    public void handle(PacketTransfer transfer, ICommandPacket packet) {

    }
}
