package org.kne.cloud.network.klalb;

import org.kne.cloud.network.ipv6.IPv6Address;
import org.kne.cloud.network.ipv6.IPv6Packet;
import org.kne.cloud.network.ipv6.IPv6Packet.IPv6Payload;
import org.kne.cloud.network.srv6.IPv6PacketConsumer;

import java.io.*;
public class KLALBProtocolRegister extends PortBinder<IPv6Packet> implements IPv6PacketConsumer {
	private static final boolean showpacket=false;
		private KLALBController controller;
		
		public KLALBProtocolRegister(KLALBController controller) {
			super(controller.getSelf().getAddress());
			this.controller = controller;
		}
		
		@Override
		public void accept(IPv6Packet packx) throws IOException {
			IPv6Payload pl = packx.getPayload();
			if (pl instanceof KLALBPacket) {
				KLALBPacket rec = (KLALBPacket) pl;
				if (showpacket)
					System.out.println("KLALB_RX:" + rec);
				if (rec instanceof PortPacket) {
					rec.setCE(packx.isCE());
					IPv6Address srcA = packx.getSourceAddress();
					PortPacket pt = (PortPacket) rec;
					BindableConsumer<IPv6Packet> cons;
					if ((cons=distributePacketToConsumer(srcA, pt))!=null) {
						cons.accept(packx);
					} else {
						if (!(pt instanceof RSTPacket)) {
							controller.getIpv6Router().enqueuePacketSendTask(() -> {
								return controller.createPacketToAddress(srcA, 0, new RSTPacket(pt.getDstPort(), pt.getSrcPort()),
										2);
							});
						}
					}
				}
			}
		}

	}