package clientP2P;

import java.util.Scanner;
import protocolP2P.Payload;
import protocolP2P.ProtocolP2PPacket;
import protocolP2P.ProtocolP2PPacketUDP;
import tools.HostItem;
import tools.Logger;
import tools.LogLevel;
import clientP2P.ClientDownloadUDP;
import clientP2P.ClientManagement;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.io.IOException;

/** Implementation of P2P-JAVA-PROJECT CLIENT
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class ClientManagementUDP extends ClientManagement {
	/** Constructor for UDP implementation, with baseDirectory, tracker, partsSubdir, logger and scanner parameters.
	 * @param baseDirectory	the root directory where files are stored
	 * @param tracker	tracker HostItem
	 * @param partsSubdir	subdirectory to store file parts
	 * @param logger	Loggger
	 * @param scanner	Scanner used to read input
	 * @param client	HostItem of the application
	 */
	public ClientManagementUDP(String baseDirectory, HostItem tracker, String partsSubdir, Logger logger, Scanner scanner, HostItem client) {
		super(baseDirectory, tracker, partsSubdir, logger, scanner, client);
	}

	/** Initialize downloader
	 * @param filename	Name of the file to download
	 */
	protected void initDownloader(String filename) {
		downLoader = (ClientDownload) new ClientDownloadUDP(filename, hostList, partsSubdir, baseDirectory, logger, client, tracker);
	}
	
	/** 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);
	}

	/** Create packets
	 * @param payload	Payload
	 */
	protected < T extends Payload > ProtocolP2PPacket<T> createProtocolP2PPacket(T payload) {
		return (ProtocolP2PPacket<T>)new ProtocolP2PPacketUDP<T>(payload);
	}

	/** Getter for tracker socket
	 * @return	Tracker's socket
	 * @throws	SocketException
	 * @throws	UnknownHostException
	 * @throws	IOException
	 */
	protected Object getTrackerSocket() throws SocketException, UnknownHostException, IOException {
		return (Object)tracker.tryGetUDPSocket();
	}

	/** Close Tracker socket
	 */
	protected void closeTrackerSocket() {
		tracker.closeUDPSocket();
	}

	/** Getter for HostItem socket
	 * @param hostItem	HostItem
	 */
	protected Object getHostItemSocket(HostItem hostItem) {
		return (Object)hostItem.getUDPSocket();
	}

	/** Close HostItem socket
	 * @param hostItem	HostItem
	 */
	protected void closeHostItemSocket(HostItem hostItem) {
		hostItem.closeUDPSocket();
	}
}
