package com.tsi.comm.server.protocol;

import com.tsi.comm.server.protocol.enums.eOpCode;
import com.tsi.comm.server.xnet.NettyUtils;
import com.tsi.comm.server.repository.TsiNodeAddManager;
import com.tsi.comm.server.vo.TsiNodeAddDetailVo;
import com.tsi.comm.server.vo.TsiNodeAddVo;
import com.tsi.comm.server.vo.TsiNodeVo;
import com.tsi.common.spring.SpringUtils;
import com.tsi.common.utils.ByteUtils;
import com.tsi.common.utils.TimeUtils;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class TsiCpuDisconnected extends TsiCpuPacket {

    private final TsiNodeAddManager nodeAddManager;
    public TsiCpuDisconnected(long nodeId, Channel channel) {
        this(nodeId, TimeUtils.currentTimeSeconds(), System.nanoTime(), channel);
    }
    public TsiCpuDisconnected(long nodeId, long msec, long nsec, Channel channel) {
        super(nodeId, msec, nsec, NettyUtils.getRemoteIpAddressToLong(channel), NettyUtils.getRemotePort(channel));
        setOpCode(eOpCode.TSI_CPU_DISCONNECTED.getValue());
        this.nodeAddManager = SpringUtils.getBean(TsiNodeAddManager.class);
    }

    protected void makeAddNodeCvimPaket(TsiCpuPacket cpuPacket) {
        final int headSize = SIZE_IPC_SIZE;
        cpuPacket.cvimData = new byte[headSize];   // ipc head only

        // cvim-raw header
        System.arraycopy(this.timespec.bytes(), 0, cpuPacket.cvimData, POS_IPC_TIMESPEC, SIZE_TIMESPEC);
        ByteUtils.setUnsignedInt(cpuPacket.cvimData, POS_IPC_IPADDR, getRemoteIp());
        ByteUtils.setUnsignedShort(cpuPacket.cvimData, POS_IPC_PORT, getRemotePort());
        cpuPacket.cvimData[POS_IPC_CONNECT] = DISCONNECT;
        ByteUtils.setUnsignedInt(cpuPacket.cvimData, POS_IPC_NODEID, cpuPacket.nodeId);
    }

    public boolean parsing(TsiNodeVo obj) {

        TsiNodeAddVo tsiNodeAddVo = this.nodeAddManager.get(this.nodeId);
        if (tsiNodeAddVo == null) {
            // 연등지 정보가 없는 경우
            makeCvimPacket();
            return true;
        }

        // 연등지 노드 카프카 패킷 생성
        for (Integer key : tsiNodeAddVo.getAddNodeMap().keySet()){
            TsiNodeAddDetailVo detailVo = tsiNodeAddVo.getAddNodeMap().get(key);
            TsiCpuAddPacket addPacket = new TsiCpuAddPacket(detailVo.getNodeId(), this.timespec, this.remoteIp, this.remotePort);
            makeAddNodeCvimPaket(addPacket);
            this.addNodes.add(addPacket);
        }
        return true;
    }

}
