package spark.pcap.io;

import java.util.List;

import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.receiver.Receiver;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.Pcaps;

public class PcapReceiver extends Receiver<String>
{

	private static final long	serialVersionUID	= 1735694675364815420L;

	public PcapReceiver()
	{
		super(StorageLevel.MEMORY_ONLY());
	}

	@Override
	public void onStart()
	{
		new Thread()
		{
			public void run()
			{
				receive();
			}
		}.start();
	}

	@Override
	public void onStop()
	{
		// DO NOTHING NOW
	}

	private void receive()
	{
		try
		{
			List<PcapNetworkInterface> nifs = Pcaps.findAllDevs();

			// XXX
			// The only way I know is to use store() to add debugging message
			// in spark streaming
			if (nifs == null || nifs.size() == 0)
			{
				String error = (nifs == null) ? "Not found any NIFs..."
						: "Found " + nifs.size() + " of NIFs";
				store(error);

				return;
			}

			// XXX
			// If Pcap.findAllDevs() returns devs, then a printed message like
			// (i am in loop..., n) in console
			while (!isStopped())
			{
				System.out.println("I am in loop...");
				store("I am in loop...\n");

				Thread.sleep(5000);
			}

			// Restart in an attempt to connect again
			// when server is active again
			restart("Trying to connect again");
		}
		catch (Throwable t)
		{
			// restart if there is any other error
			restart("Error receiving data", t);
		}
	}

}
