package com.its.pis.xnetudp.thread;

import com.its.app.AppUtils;
import com.its.pis.domain.NET;
import com.its.pis.entity.TbUnitSyst;
import com.its.pis.entity.TbVdsCtlr;
import com.its.pis.global.AppRepository;
import com.its.pis.service.UnitSystService;
import com.its.pis.xnetudp.protocol.CENTER_COMM_DEFINE;
import com.its.pis.xnetudp.protocol.CENTER_COMM_MESSAGE;
import com.its.pis.xnetudp.protocol.CENTER_VDS_REQ_RESET;
import com.its.pis.xnetudp.protocol.CENTER_VDS_REQ_STOPIMAGE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class CenterCommServerReceiver extends AbstractCenterCommServerReceiver {

    @Async("centerCommExecutor")
    public void run(CENTER_COMM_MESSAGE data) {
        if (data == null) {
            log.error("CenterCommServerReceiver: RECV Data Packet NULL");
            return;
        }
        if (data.getRecvId() != CENTER_COMM_DEFINE.INT_ID_VDS_SERVER) {
            log.error("CenterCommServerReceiver: UDP RECV UNKNOWN SERVER ID: {}", data.getRecvId());
            return;
        }

        String reqIpAddr = data.getSenderIp();
        int reqPort = 4603;
        UnitSystService unitSystService = (UnitSystService) AppUtils.getBean(UnitSystService.class);
        ConcurrentHashMap<String, TbUnitSyst> untiSystMap = unitSystService.getUnitSystMap();
        for (Map.Entry<String, TbUnitSyst> e : untiSystMap.entrySet()) {
            if (reqIpAddr.equals(e.getValue().getSYST_IP_1())) {
                reqPort = e.getValue().getPRGM_PORT();
                break;
            }
        }

        byte opCode = data.getOpCode();
        if (opCode == CENTER_COMM_DEFINE.INT_OP_VDS_RESET) {
            CENTER_VDS_REQ_RESET req = new CENTER_VDS_REQ_RESET(data.getBody());
            log.info("CenterCommServerReceiver: VDS REQ RESET: [{}] [{}] [{}]", req.getCmdTime(), req.getOperId(), req.getVdsCtlrNmbr());

            TbVdsCtlr vds = AppRepository.getInstance().getCtlrMap().get(req.getVdsCtlrNmbr());
            if (vds == null) {
                log.error("CenterCommServerReceiver: VDS REQ RESET Unknown VDS: [{}]", req.getVdsCtlrNmbr());
                return;
            }
            if (vds.getChannel() == null || vds.getNetState() == NET.CLOSED) {
                log.error("CenterCommServerReceiver: VDS REQ RESET Not Connect: [{}]", vds);
                return;
            }

//            vds.setCliReq(new InetSocketAddress(reqIpAddr, reqPort));
//            VDS_REQ_HEAD reqHdr = new VDS_REQ_HEAD();
//            byte[] headBytes = reqHdr.makeHead(VDS_HEAD.evds_Reset, vds, 9);
//            ByteBuffer sendBuff = ByteBuffer.allocate(VDS_REQ_HEAD.VDS_REQ_HEADER_SIZE + reqHdr.getLength());
//            log.info("CenterCommServerReceiver: [{}], SEND-evds_Reset: {}, {}, {}", vds.getVDS_CTLR_NMBR(), reqHdr.getLength(), headBytes.length, sendBuff.capacity());
//            sendBuff.order(ByteOrder.BIG_ENDIAN);
//            sendBuff.put(headBytes);
//            ChannelFuture f = vds.getChannel().writeAndFlush(sendBuff);
//            f.awaitUninterruptibly();
//            if (f.isDone() || f.isSuccess()) {
//                log.info("SEND_0: [{}], evds_Reset: {} headBytes, {} sendBytes. [{}]", vds.getVDS_CTLR_IP(), headBytes.length, sendBuff.array().length, vds.getVDS_CTLR_ID());
//            } else {
//                log.error("SEND_0: [{}], evds_Reset: {} headBytes, {} sendBytes, Failed. [{}]", vds.getVDS_CTLR_IP(), headBytes.length, sendBuff.array().length, vds.getVDS_CTLR_ID());
//            }
        } else if (opCode == CENTER_COMM_DEFINE.INT_OP_VDS_STOP_IMAGE_REQ) {
            CENTER_VDS_REQ_STOPIMAGE req = new CENTER_VDS_REQ_STOPIMAGE(data.getBody());
            log.info("CenterCommServerReceiver: VDS REQ STOP IMAGE: [{}] [{}] [{}] [{}]", req.getCmdTime(), req.getOperId(), req.getVdsCtlrNmbr(), req.getCameraNo());

            TbVdsCtlr vds = AppRepository.getInstance().getCtlrMap().get(req.getVdsCtlrNmbr());
            if (vds == null) {
                log.error("CenterCommServerReceiver: VDS REQ STOP IMAGE Unknown VDS: [{}]", req.getVdsCtlrNmbr());
                return;
            }
            if (vds.getChannel() == null || vds.getNetState() == NET.CLOSED) {
                log.error("CenterCommServerReceiver: VDS REQ STOP IMAGE Not Connect: [{}]", vds);
                return;
            }

//            vds.setCliReq(new InetSocketAddress(reqIpAddr, reqPort));
//            VDS_REQ_HEAD reqHdr = new VDS_REQ_HEAD();
//            byte[] headBytes = reqHdr.makeHead(VDS_HEAD.evds_StopImage, vds, 10);
//            ByteBuffer sendBuff = ByteBuffer.allocate(VDS_REQ_HEAD.VDS_REQ_HEADER_SIZE + reqHdr.getLength());
//            sendBuff.order(ByteOrder.BIG_ENDIAN);
//            sendBuff.put(headBytes);
//            sendBuff.put(req.getCameraNo());
//            ChannelFuture f = vds.getChannel().writeAndFlush(sendBuff);
//            f.awaitUninterruptibly();
//            if (f.isDone() || f.isSuccess()) {
//                log.info("SEND_0: [{}], evds_StopImage: {} headBytes, {} sendBytes. [{}]", vds.getVDS_CTLR_IP(), headBytes.length, sendBuff.array().length, vds.getVDS_CTLR_ID());
//            } else {
//                log.error("SEND_0: [{}], evds_StopImage: {} headBytes, {} sendBytes, Failed. [{}]", vds.getVDS_CTLR_IP(), headBytes.length, sendBuff.array().length, vds.getVDS_CTLR_ID());
//            }
        } else {
            log.error("CenterCommServerReceiver: UDP RECV UNKNOWN MESSAGE: {}", opCode);
        }
    }
}
