package com.its.dsrc.xnettcp.dsrc.process.response;

import com.beanit.asn1bean.ber.types.BerEnum;
import com.beanit.asn1bean.ber.types.BerInteger;
import com.beanit.asn1bean.ber.types.BerOctetString;
import com.beanit.asn1dsrc.dsrc.C2CAuthenticatedMessage;
import com.beanit.asn1dsrc.dsrc.PDUs;
import com.beanit.asn1dsrc.dsrc.Reject;
import com.beanit.asn1dsrc.dsrc.RejectType;
import com.beanit.asn1dsrc.enums.eAuthInfo;
import com.beanit.asn1dsrc.enums.ePdusPr;
import com.beanit.asn1dsrc.util.DsrcAsn1Utils;
import com.its.app.utils.NettyUtils;
import com.its.dsrc.entity.TbRseCtlr;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DsrcAsn1Reject {

    static C2CAuthenticatedMessage makeC2CAuthenticatedMessage(TbRseCtlr obj, Channel channel, C2CAuthenticatedMessage c2c, int rejectType) {
        if (obj == null || channel == null || c2c == null) {
            log.info("{}. {} {}, {}", "makeC2CAuthenticatedMessage", obj, channel, c2c);
            return null;
        }

        String ipAddress = NettyUtils.getRemoteIpAddress(channel);
        log.info("DsrcAsn1Reject.makeC2CAuthenticatedMessage: {}", ipAddress);

        C2CAuthenticatedMessage resC2c = null;
        ePdusPr pdu = DsrcAsn1Utils.getPduChoice(c2c.getPdu());

        byte[] reject = { (byte) eAuthInfo.AI_Reject.getValue() };
        PDUs resPdus = new PDUs();
        Reject rjt = new Reject();
        RejectType rjtType = new RejectType();

        switch(pdu) {
            case PDUs_PR_login:
                resC2c = new C2CAuthenticatedMessage();
                rjtType.setDatexRejectLoginCd(new BerEnum(rejectType));
               break;
            case PDUs_PR_subscripiton:
                resC2c = new C2CAuthenticatedMessage();
                rjtType.setDatexRejectSubscriptionCd(new BerEnum(rejectType));
                break;
            case PDUs_PR_publication:
                resC2c = new C2CAuthenticatedMessage();
                rjtType.setDatexRejectPublicationCd(new BerEnum(rejectType));
                break;
            default:
                break;
        }

        if (resC2c != null) {
            rjt.setDatexRejectPacketNbr(c2c.getDatexDataPacketNumber());
            rjt.setDatexRejectType(rjtType);
            resPdus.setReject(rjt);

            resC2c.setDatexAuthenticationInfoText(new BerOctetString(reject));
            resC2c.setDatexDataPacketNumber(new BerInteger(obj.getSeq().nextValue()));
            resC2c.setDatexDataPacketPriorityNumber(new BerInteger(1));
            //resC2c.setOptions(DsrcAsn1Utils.swapHeaderOptions(c2c.getOptions()));
            resC2c.setOptions(DsrcAsn1Utils.swapHeaderOptions(obj.getHeaderOptions()));
            resC2c.setPdu(resPdus);
        }
        return resC2c;
    }
}
