package UdpMulticastHttpExamples;

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

/**
 * Looks a lot like UdpReceiver. Start this before launching MulticastSender.
 *
 * @author mcgredo
 * @author brutzman
 */
public class MulticastReceiver {

    // 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
    public static final String MULTICAST_ADDRESS = "239.1.2.15";
    public static final int DESTINATION_PORT = 1718;

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

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

    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("MulticastReceiver 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 = DisThreadedNetIF.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(MulticastSender.QUIT_SENTINEL)) {
                    System.out.println("Received sentinel \"" + MulticastSender.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);
            }
        } 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(MulticastReceiver.class.getName()).log(Level.SEVERE, null, ex);
                }
                multicastSocket.close();
            }
            // socket/database/completion cleanup code can go here, if needed.
            System.out.println("MulticastReceiver finally block, complete.");
        }
    }
}