package serverP2P;
import tools.Logger;
import tools.LogLevel;
import protocolP2P.ProtocolP2PPacket;
import protocolP2P.ProtocolP2PPacketUDP;
import protocolP2P.Register;
import protocolP2P.Payload;
import tools.HostItem;

/** Class allowing to keep the tracker informed about file list (UDP impl.)
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class FileWatcherUDP extends FileWatcher {

	/** Constructor
	 * @param logger	Logger
	 * @param millis	Time interval before recheck
	 * @param server	HostItem for the server
	 * @param tracker	HostItem for the tracker
	 * @param baseDirectory	Directory to search files
	 */
	public FileWatcherUDP(Logger logger, long millis, HostItem server, HostItem tracker, String baseDirectory) {
		super(logger, millis, server, tracker, baseDirectory);
		assert logger != null : "Logger is null";
		assert server != null : "Server is null";
		assert tracker != null : "Tracker is null";
		assert baseDirectory != null : "baseDirectory is null";
	}

	/** Implementation of writeLog
	 * @param text	Text to log
	 * @param logLevel	level of logging
	 */
	protected void writeLog(String text, LogLevel logLevel) {
		logger.writeUDP(text, logLevel);
	}

	/** Implementation of writeLog
	 * @param e	exception to log
	 * @param logLevel	level of logging
	 */
	protected void writeLog(Exception e, LogLevel logLevel) {
		logger.writeUDP(e, logLevel);
	}

	/** Register server on tracker
	 */
	protected void registerTracker() {
		try {
			writeLog("Trying to register into tracker", LogLevel.Info);
			ProtocolP2PPacket<Register> p = (ProtocolP2PPacket<Register>)new ProtocolP2PPacketUDP<Register>(new Register(server));
			p.sendRequest((Object)tracker.tryGetUDPSocket());
			writeLog("Register request sent (but cannot ensure reception).", LogLevel.Debug);
			tracker.closeUDPSocket();
		} catch (Exception e) {
			force = true;
			writeLog("Cannot contact tracker, trying again at next iteration (" + time + " milliseconds).", LogLevel.Error);
		}
	}

}
