package de.lazyzero.kkMulticopterFlashTool.utils;

import gnu.io.CommPortIdentifier;

import java.util.Vector;

import de.lazyzero.kkMulticopterFlashTool.KKMulticopterFlashTool;

/**
 * @author moll
 *
 */
public class PortScanner {
	
	
	/**
	 * @return List of all serial ports + the usb port
	 */
	public static Vector<String> listProgrammerPorts(){
		Vector<String> ports = new Vector<String>();
		ports.add("usb");
		ports.addAll(listSerialPorts());
		ports.addAll(listParallelPorts());
		return ports;
	}
	
	
	 /**
	 * @return List all serial ports
	 */
	public static Vector<String> listSerialPorts()
	    {
		 	Vector<String> ports = new Vector<String>();
		 	if (KKMulticopterFlashTool.ENABLE_PORT_CHECK) {
		 		java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
		 		while ( portEnum.hasMoreElements() ) 
		 		{
		 			CommPortIdentifier portIdentifier = portEnum.nextElement();
		 			if (portIdentifier.getPortType()==CommPortIdentifier.PORT_SERIAL){
		 				if (System.getProperty("os.name").toLowerCase().contains("mac")) {
		 					if (portIdentifier.getName().contains("cu")){
		 						ports.add(portIdentifier.getName());
		 					}
		 				} else {
		 					ports.add(portIdentifier.getName());
		 				}
		 			}
		 		} 
		 	}
	        return ports;
	    }
	    
	 /**
	 * @return List all parallel ports
	 */
	public static Vector<String> listParallelPorts()
	    {
		 	Vector<String> ports = new Vector<String>();
		 	
		 	if (KKMulticopterFlashTool.ENABLE_PORT_CHECK) {
		 		java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
		 		while ( portEnum.hasMoreElements() ) 
		 		{
		 			CommPortIdentifier portIdentifier = portEnum.nextElement();
		 			if (portIdentifier.getPortType()==CommPortIdentifier.PORT_PARALLEL){
//	            	if (System.getProperty("os.name").toLowerCase().contains("mac")) {
//	            		if (portIdentifier.getName().contains("cu")){
//	            			ports.add(portIdentifier.getName());
//	            		}
//	            	} else {
		 				if (System.getProperty("os.name").toLowerCase().contains("windows")) {
		 					ports.add(portIdentifier.getName().toLowerCase());
		 				} else {
		 					ports.add(portIdentifier.getName());
		 				}
//	            	}
		 			}
		 		} 
		 	}
	        return ports;
	    }
	
}

