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

import java.awt.Container;
import java.io.File;

import javax.swing.JFileChooser;

import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.ClassImportException;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.ImportController;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.util.JavaFileFilter;

/**
 * Import PopUp which allows selection of a java File which should be compiled and be a subclass of T. Throws ClassImportExceptions on failures, and returns null if importing was aborted.
 *
 * @author Andreas T. Meyer-Berg
 * @param <T> Interface/Class which should be superclass of imported
 */
public class ImportPopUp<T> {

	private Container panel;
	private Class<T> classType;
	
	/**
	 * Creates ImportPopUp
	 * @param panel position relative to this panel
	 * @param classType superclass/interface of the imported class
	 */
	public ImportPopUp (Container panel, Class<T> classType) {
		this.panel = panel;
		this.classType = classType;
	}
	
	/**
	 * Creates PopUp to import an java File, returns the class of this file
	 * 
	 * @return Class of imported File, which is subclass of T, null on abort
	 * @throws ClassImportException on Errors
	 */
	public  Class<? extends T> showPopUp() throws ClassImportException{
		JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
		fc.setFileFilter(new JavaFileFilter());
		int returnVal = fc.showOpenDialog(panel);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
        	/**
        	 * selected File
        	 */
            File file = fc.getSelectedFile();
            String[] parts = file.getName().split("[.]");
            if(parts.length <= 1)
            	throw new ClassImportException("Invalid fileName: "+file.getName()+" missing Name.java Format");
            /**
             * Check the file type ending
             */
            String ending = parts[parts.length-1].toLowerCase();
            if(ending.equals("java")){
            	// Compile source file.
            	/**
            	 * Imported Java Class
            	 */
            	Class<?> imported = null;
				imported = ImportController.importJavaClass(file);
				
				if(imported == null)
					throw new ClassImportException("Importing javaClass failed");

				try {
					/**
					 * If valid subclass
					 */
					return imported.asSubclass(classType);	
				} catch (ClassCastException e) {
					throw new ClassImportException("Class does not implement "+classType.getSimpleName());
				}
            }else{
            	/**
            	 * Invalid file name
            	 */
            	throw new ClassImportException("Invalid fileEnding: \""+ending+"\" instead of \"java\"");
            }
        } else {
           //Importing Cancelled by user
        	return null;
        }
	}
}
