/**
 * DeviceFactory.java
 * Created Dec 29, 2008
 * Copyright (c) Tandberg Television 2008
 */
package com.tandbergtv.workflow.comm.internal;

import java.net.MalformedURLException;

import org.apache.log4j.Logger;

import com.tandbergtv.workflow.comm.HTTPDevice;
import com.tandbergtv.workflow.comm.IDevice;
import com.tandbergtv.workflow.comm.TCPDevice;

/**
 * Creates devices
 * 
 * @author Sahil Verma
 */
public class DeviceFactory {

	private static final Logger logger = Logger.getLogger(DeviceFactory.class);

	/**
	 * Creates and returns a new instance of the factory
	 * 
	 * @return
	 */
	public static DeviceFactory newInstance() {
		return new DeviceFactory();
	}

	/**
	 * Creates a device
	 * 
	 * @param url the URL of the device 
	 * @return the device created
	 * @throws MalformedURLException 
	 */
	public IDevice createDevice(String url) throws MalformedURLException {
		return createDevice(url, null);
	}
	
	/**
	 * Creates a device using the specified URL, e.g. http://www.ibm.com or tcp://cs.rin.ru:27015,
	 * with the specified name
	 * 
	 * @param url the URL of the device
	 * @param name the name of the device
	 * @return the device created
	 * @throws MalformedURLException
	 */
	public IDevice createDevice(String url, String name) throws MalformedURLException {
		logger.debug("Creating device for url " + url);

		if (url.startsWith("tcp://") || url.startsWith("net.tcp://")) {
			String [] components = url.split("tcp://");
			String [] hostAndPort = components[1].split(":");
			
			String ip = hostAndPort[0];
			int port = 0;
			
			if (hostAndPort.length == 2)
				port = Integer.parseInt(hostAndPort[1]);
			
			return new TCPDevice(ip, port, name);
		}

		if (url.startsWith("http://") || url.startsWith("https://"))
			return new HTTPDevice(url, name);

		throw new MalformedURLException("URL " + url + " is not supported");
	}
}
