package MV3500Cohort2023MarchJune.homework2.Chojnacki;

import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Modified the receiver to close after receiving 10 packets.
 *
 * @author Bruce Chojnacki
 */
public class MulticastUdpReceiver
{
    /** Default constructor */
    public MulticastUdpReceiver()
    {
        // default constructor
    }
    // reserved range for all IPv4 multicast: 224.0.0.0 through 239.255.255.255
    // https://en.wikipedia.org/wiki/Multicast_address
    // https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml
    private static final String MULTICAST_ADDRESS = "239.1.2.15";
    private static final int     DESTINATION_PORT = 1718;

    /**
     * Time to live: how many router-decrement levels can be crossed
     */
    private static final int TTL = 10;

    private static final boolean INFINITE_READ_LOOP = true;
    private static NetworkInterface ni;

    /**
     * Program invocation, execution starts here
     * @param args command-line arguments
     */
    public static void main(String[] args)
    {
        MulticastSocket multicastSocket = null;
        InetSocketAddress group = null;
        ByteBuffer buffer = ByteBuffer.allocate(1500);
        DatagramPacket packet = new DatagramPacket(buffer.array(), buffer.capacity());
        
        try {
            System.out.println("UdpExamples.MulticastUdpReceiver started...");

            // This is a java/IPv6 problem. You should also add it to the
            // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true
            // set in the "run" section of preferences. Also, typically
            // netbeans must be restarted after these settings.
            // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache
            System.setProperty("java.net.preferIPv4Stack", "true");

            multicastSocket = new MulticastSocket(DESTINATION_PORT);
            multicastSocket.setTimeToLive(TTL);
            InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS);
            
            group = new InetSocketAddress(multicastAddress, DESTINATION_PORT);
            
            // Join group useful on receiving side
            multicastSocket.joinGroup(group, ni = DisThreadedNetworkInterface.findIpv4Interface());
            // You can join multiple groups here
            
            System.out.println("Multicast address/port: " + multicastAddress.getHostAddress() + "/" + DESTINATION_PORT);
            System.out.println("Multicast packets received log:");

            int index, count = 0; // initialize
            float firstFloat, secondFloat;
            StringBuilder firstCharacters = new StringBuilder();
            char nextChar;

            while (true) {
                multicastSocket.receive(packet);
                count++;

                nextChar = ' ';
                while (nextChar != ';') // read and build string until terminator ; found
                {
                    nextChar = buffer.getChar();
                    firstCharacters.append(nextChar);
                }
                if (firstCharacters.toString().contains(MulticastUdpSender.QUIT_SENTINEL)) {
                    System.out.println("Received sentinel \"" + MulticastUdpSender.QUIT_SENTINEL + "\"");
                    if (!INFINITE_READ_LOOP) {
                        break; // exit out of reading loop
                    }
                }
                index = buffer.getInt();
                firstFloat = buffer.getFloat();
                secondFloat = buffer.getFloat();
                buffer.clear();

                if (count < 10) {
                    System.out.print(" "); // prettier output formatting
                }
                System.out.print(count + ". \"" + firstCharacters + "\" "); // wrap string in quote marks
                System.out.println("index=" + index + ", firstFloat=" + firstFloat + " secondFloat=" + secondFloat);

                System.out.println("MulticastReceiver loop complete.");
                firstCharacters.setLength(0);
                if (count >= 10) {
                    break;
                }
            }
        } catch (IOException e) {
            System.err.println("Problem with MulticastReceiver, see exception trace:");
            System.err.println(e);
        } finally // clean up after exit condition
        {
            if (multicastSocket != null && !multicastSocket.isClosed()) {
                try {
                    multicastSocket.leaveGroup(group, ni);
                } catch (IOException ex) {
                    Logger.getLogger(MulticastUdpReceiver.class.getName()).log(Level.SEVERE, null, ex);
                }
                multicastSocket.close();
            }
            // socket/database/completion cleanup code can go here, if needed.
            System.out.println("MulticastReceiver has received all of the packets!");
        }
    }
}