package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.popups;

import java.awt.Component;
import java.util.Collection;
import java.util.LinkedList;

import javax.swing.JDialog;

import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;

/**
 * PopUp for the creation of Connections
 * 
 *
 * @author Andreas T. Meyer-Berg
 */
@SuppressWarnings("serial")
public class ConnectionCreationDialog extends JDialog {
	private ConnectionCreationPanel content;
	private Component parent;

	/**
	 * Create a Dialog for editing the given Connection
	 * @param connection Connection to be edited
	 * @param controller Controller for changing the connection
	 * @param panel Panel the PopUp should be moved relative to
	 */
	public ConnectionCreationDialog(Connection connection, Controller controller, Component panel) {
		super();
		content = new ConnectionCreationPanel(connection, controller, this);
		parent = panel;
		initialize();
	}
	
	/**
	 * Create a Dialog for creating a Connection of the given devices
	 * @param devices ports which should be connected
	 * @param link Link which the connection should run on
	 * @param controller Controller for changing the connection
	 * @param panel Panel the PopUp should be moved relative to
	 */
	public ConnectionCreationDialog(Collection<Port> devices, Link link, Controller controller, Component panel){
		super();
		content = new ConnectionCreationPanel(devices, link, controller, this);
		parent = panel;
		initialize();
	}
	/**
	 * Initializes and shows a creation dialog for a connection of the given devices
	 * @param devices Devices, which should be connected
	 * @param controller Controller for changing the connection
	 * @param panel Panel the PopUp should be moved relative to
	 */
	public ConnectionCreationDialog(Collection<SmartDevice> devices, Controller controller, Component panel){
		super();
		LinkedList<Port> ports = new LinkedList<Port>();
		for(SmartDevice d: devices)
			ports.add(new Port(d, (short) 12));
		Link link = null;
		/**
		 * Find common link -> else null -> create new link
		 */
		for(Link l:controller.getNetworkController().getLinks()){
			if(l.getDevices().containsAll(devices)){
				link = l;
				break;
			}
		}
		content = new ConnectionCreationPanel(ports, link, controller, this);
		parent = panel;
		initialize();
	}

	/**
	 * Initialize and show the popUp
	 */
	private void initialize() {
		this.setModal(true);
		this.setContentPane(content);
		this.pack();
		setLocationRelativeTo(parent);
		this.setVisible(true);
	}
}
