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

/** Class allowing to keep the tracker informed about file list (TCP impl.)
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class FileWatcherTCP 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 FileWatcherTCP(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.writeTCP(text, logLevel);
	}

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

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

}
