/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.core.gui;


import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.settings.SettingsPlugin;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * <p>This class implements the Settings dialog for the configuration of the
 * GECAMed Modules. You can enable / disable the different Modules here. It
 * implements the lu.tudor.santec.settings.SettingsPlugin Interface and is used
 * inside the framework with the SettingPanel.</p>
 * <p>All methods are implemented that are necessary to support all functions of
 * the SettingsPlugin.</p>
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @Version
 * <br>$Log: ModuleManagerPlugin.java,v $
 * <br>Revision 1.15  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.14  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.13  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.12  2008-08-19 10:25:08  heinemann
 * <br>cleanup
 * <br>
 * <br>Revision 1.11  2008-04-08 09:26:10  hermen
 * <br>fixed bug of modules not showing
 * <br>
 * <br>Revision 1.10  2008-03-25 07:13:56  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.9  2008-03-13 10:11:46  hermen
 * <br>fixed translations
 * <br>
 * <br>Revision 1.8  2008-01-15 09:29:39  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 * <br>Revision 1.7  2007-12-03 10:59:02  hermen
 * <br>updated Javadoc
 * <br>
 *
 */
public class ModuleManagerPlugin extends SettingsPlugin implements ActionListener, ListSelectionListener {
    
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(ModuleManagerPlugin.class
			.getName());
	
    public static final String ENABLED_MODULES = "EnabledModules";
    public static final String DISABLED_MODULES = "DisabledModules";
    public static final String NAME = "ModuleManager";
    
    /**
     * file to configure the available modules and their defaults
     */
    private static final URL CONFIG_FILE = ModuleManagerPlugin.class.getResource("ModuleManagerPlugin.properties");
	
	private static final long serialVersionUID = 1L;
	private JPanel          m_ModulePanel;
    private JLabel          m_CommentLabel;
    private JLabel          m_ModulesLabel;
    private JList           m_ModulesList;
    private JButton         m_EnableButton;
    private JButton         m_DisableButton;
    private JButton         m_UpButton;
    private JButton         m_DownButton;
    
    private Vector<ModuleElement> m_modules = new Vector<ModuleElement>();
    
    JLabel descriptionLabel = new JLabel("");
	private String enabledModules = "";
	private String disabledModules = "";
	private String line;
    
    /**
     * This Methode creates a new object of the ModuleManagerPlugin.
     */
    public ModuleManagerPlugin() {
        super(NAME);
        FormLayout              l_Layout;
        PanelBuilder            l_Builder;
        CellConstraints         l_Constraints;
        
        // Create Module Managers SubPanel
        
        l_Layout      = new FormLayout("fill:120dlu:grow, 1dlu, fill:50dlu:grow, 1dlu",
                "pref, 5dlu, pref, pref, pref, pref, pref, 30dlu, 2dlu");
        
        l_Constraints = new CellConstraints();
        
        m_ModulePanel = createSubPanel(Translatrix.getTranslationString("ModulesManagerPlugin.ModuleManager"));
        m_ModulePanel.setLayout(l_Layout);
        
        l_Builder     = new PanelBuilder(l_Layout,m_ModulePanel);
        
        // init the components:
        
        m_CommentLabel = new JLabel(Translatrix.getTranslationString("ModulesManagerPlugin.Comment"));
        m_ModulesLabel = new JLabel(Translatrix.getTranslationString("ModulesManagerPlugin.availableModules"));
        
        m_ModulesList = new JList();
        m_ModulesList.setCellRenderer(new ModuleFormatterJListRenderer());
        m_ModulesList.addListSelectionListener(this);
        m_ModulesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        m_ModulesList.setSelectedIndex(0);
        
        m_EnableButton = new JButton(Translatrix.getTranslationString("ModulesManagerPlugin.enable"));
        m_EnableButton.addActionListener(this);
        m_DisableButton = new JButton(Translatrix.getTranslationString("ModulesManagerPlugin.disable"));
        m_DisableButton.addActionListener(this);
        m_UpButton = new JButton(GECAMedModule.getSmallIcon(GECAMedModule.UP));
        m_UpButton.addActionListener(this);
        m_DownButton = new JButton(GECAMedModule.getSmallIcon(GECAMedModule.DOWN));
        m_DownButton.addActionListener(this);
        
        l_Builder.add(m_CommentLabel,l_Constraints.xyw(1,1,3));
        l_Builder.add(m_ModulesLabel,l_Constraints.xyw(1,3,1));
        l_Builder.add(new JScrollPane(m_ModulesList),l_Constraints.xywh(1,4,1,5));
        l_Builder.add(m_EnableButton,l_Constraints.xyw(3,4,1));
        l_Builder.add(m_DisableButton,l_Constraints.xyw(3,5,1));
        l_Builder.add(m_UpButton,l_Constraints.xyw(3,6,1));
        l_Builder.add(m_DownButton,l_Constraints.xyw(3,7,1));
        
        addSubPanel(m_ModulePanel);
        
        setIcon(GECAMedModule.getIcon(GECAMedModule.MODULES));
        setLabel(Translatrix.getTranslationString("ModulesManagerPlugin.ModuleManager"));
        
        loadAvailableModules(CONFIG_FILE);
        setStationary(ENABLED_MODULES, enabledModules);
        setStationary(DISABLED_MODULES, disabledModules);
        
        
    }
    
    
    /**
     * Is called if the default settings file is specified and used.
     */
    public void revertToDefaults() {
        setValue(ENABLED_MODULES,  getDefault(ENABLED_MODULES));
        setValue(DISABLED_MODULES,  getDefault(DISABLED_MODULES));
        
        reflectSettings();
        
        super.revertToDefaults();
    }
    
//---------------------------------------------------------------------------
    
    /**
     * Updates the Settings in the settings file. This methode is called if the apply
     * or OK button is pressed.
     */
    public void updateSettings() {
        
        resetValueChanged();
        
        setValue(ENABLED_MODULES,  getEnabledModules());
        setValue(DISABLED_MODULES, getDisabledModules());
        
        super.updateSettings();
    }
    
    public void init(){
        
       
    }
    
//---------------------------------------------------------------------------
    
    /**
     * Updates the GUI with the values in the settings file. The methode is called,
     * if the cancel button is pressed or the dialog is created.
     */
    public void reflectSettings() {
        
//    	 create a vector with the enabled / disabled elements: m_modules
        m_modules = new Vector<ModuleElement>();

        // modules enabled in db
        Collection<String> l_enabledModules = Arrays.asList(((String)getValue(ENABLED_MODULES)).split(" "));
        
        // modules enabled in file
        Collection<String> defaultEnabledModules = Arrays.asList(((String)getStationary(ENABLED_MODULES)).split(" "));
        
        // modules disabled in db
//        Collection<String> l_disabledModules = Arrays.asList(((String)getValue(DISABLED_MODULES)).split(" "));
        
        // modules disables in db
        Collection<String> defaultDisabledModules = Arrays.asList(((String)getStationary(DISABLED_MODULES)).split(" "));

//        Collection<String> deleteables = new ArrayList<String>(); 
//        for (Iterator iter = l_enabledModules.iterator(); iter.hasNext();) {
//			String mod = (String) iter.next();
//			if (! defaultDisabledModules.contains(mod) && ! defaultDisabledModules.contains(mod))
//				deleteables.add(mod);
//		}
//        l_enabledModules.removeAll(deleteables);
//        
//        deleteables.clear();
//        for (Iterator iter = l_disabledModules.iterator(); iter.hasNext();) {
//			String mod = (String) iter.next();
//			if (! defaultDisabledModules.contains(mod) && ! defaultDisabledModules.contains(mod))
//				deleteables.add(mod);
//		}
//        l_disabledModules.removeAll(deleteables);
        
        // list of all modules in the files
        Collection<String> newModules = new ArrayList<String>();
        newModules.addAll(defaultEnabledModules);
        newModules.addAll(defaultDisabledModules);
        
        // remove the db enabled ones
        newModules.removeAll(l_enabledModules);
        
        // remove the db disabled ones
//        newModules.removeAll(l_disabledModules);
       
        
        // a) enabled:
        for (Iterator iter = l_enabledModules.iterator(); iter.hasNext();) {
			String l_module = (String) iter.next();
			if (l_module.length() > 3) {
				ModuleElement l_element = new ModuleElement(l_module, true);
	            m_modules.add(l_element);
			}
		}
        
        // b) disabled:
        for (Iterator iter = newModules.iterator(); iter.hasNext();) {
        	String l_module = (String) iter.next();
        	if (l_module.length() > 3) {
	            ModuleElement l_element = new ModuleElement(l_module, false);
	            m_modules.add(l_element);
        	}
        }
        
        m_ModulesList.setListData(m_modules);
        m_ModulesList.setSelectedIndex(0);
        
        super.reflectSettings();
    }
    
    
//---------------------------------------------------------------------------
    
    //---------------------------------------------------------------------------
    private void loadAvailableModules(URL url) {
		try {
			BufferedReader br = new BufferedReader(
					new InputStreamReader(url.openStream()));
			while ((line = br.readLine()) != null) {
				if (!line.startsWith("#") && line.length() > 3) {
					try {
						String[] fields = line.split("=");

						if (fields[1].toLowerCase() .equals("on")) {
							this.enabledModules += fields[0] + " ";
						} else {
							this.disabledModules += fields[0] + " ";
						}
					} catch (Exception e) {
						logger.log(Level.WARN, "line is no valid settingline: " + line);
					}
				}
			}
		} catch (Exception e) {
			logger.log(Level.WARN, "error parsing file ", e);
		}
	}
    
    // ---------------------------------------------------------------------------
    
    /**
     * Methode to handle the ActionEvents for the Buttons on the Panel.
     * @param p_ActionEvent The ActionEvent.
     */
    public void actionPerformed(ActionEvent p_ActionEvent) {
        
        if (p_ActionEvent.getSource() == m_EnableButton) {
            // get selected Element:
            ModuleElement e = (ModuleElement) m_ModulesList.getSelectedValue();
            
            // change the value to "true":
            e.setEnabled(true);
            
            int l_currentLocation = m_ModulesList.getSelectedIndex();
            m_ModulesList.setSelectedIndex((l_currentLocation+1));
            
            m_ModulesList.repaint();
        }
        
        if (p_ActionEvent.getSource() == m_DisableButton) {
            // get selected Element:
        	ModuleElement e = (ModuleElement) m_ModulesList.getSelectedValue();
            
            // change the value to "true":
        	e.setEnabled(false);
            
            int l_currentLocation = m_ModulesList.getSelectedIndex();
            m_ModulesList.setSelectedIndex((l_currentLocation+1));
            
            m_ModulesList.repaint();
        }
        
        if (p_ActionEvent.getSource() == m_UpButton) {
            
            int l_currentLocation = m_ModulesList.getSelectedIndex();
            ModuleElement o = (ModuleElement)  m_ModulesList.getModel().getElementAt(l_currentLocation);
            
            if(o != m_modules.firstElement()){
                
                // remove element at selected location:
                m_modules.remove(o);
                
                // add it to selected location - 1:
                m_modules.add((l_currentLocation-1), o);
                m_ModulesList.setSelectedIndex((l_currentLocation-1));
                
                
                m_ModulesList.repaint();
            }
        }
        
        if (p_ActionEvent.getSource() == m_DownButton) {
            int l_currentLocation = m_ModulesList.getSelectedIndex();
            ModuleElement o = (ModuleElement)  m_ModulesList.getModel().getElementAt(l_currentLocation);
            
            if(o != m_modules.lastElement()){
                
                // remove element at selected location:
                m_modules.remove(o);
                
                // add it to selected location - 1:
                m_modules.add((l_currentLocation+1), o);
                m_ModulesList.setSelectedIndex((l_currentLocation+1));
                
                m_ModulesList.repaint();
            }
        }
        
    }
    
    /**
     * Methode that implements the ListChangeListner.valueChanged(ListSelectionEvent).
     * Used to display the list properly.
     * @param p_SelectioEvent The Selection Event.
     */
    public void valueChanged(ListSelectionEvent p_SelectioEvent){        
        try {
            // get selected element:
//        	ModuleElement e = (ModuleElement)  m_ModulesList.getSelectedValue();

        	
//            // call the getDescription static method:
//            Class c = Class.forName(e.getName());
//            
//            Method m = c.getMethod("getDescription", null);
//            Object o = m.invoke(null, null);
//            
//            // display it in the Description area:
//            m_ModuleDescriptionLabel.setText("<html>" + (String)o + "</html>");
//            m_ModuleDescriptionLabel.repaint();
        } catch (Exception ioe) {
            // this does not matter.....
        } 
    }
    
    /**
     * Returns the currently in the Selection list enabled Modules.
     * @return A space separated list of enabled modules.
     */
    public String getEnabledModules(){
        
        String l_result = "";
        
        // walk over all modules:
        int l_numberOfElements = m_ModulesList.getModel().getSize();
        
        for(int i = 0; i < l_numberOfElements; i++){
        	ModuleElement e = (ModuleElement) m_ModulesList.getModel().getElementAt(i);
            
            // if they are enabled, add the class names to the result
            if(e.isEnabled()){
                l_result += e.getName() + " ";
            }
        }
        
        // ok, done:
        return l_result;
    }
    
    /**
     * Returns the currently in the Selection list disabled Modules.
     * @return A space separated list of disabled modules.
     */
    public String getDisabledModules(){
        
        String l_result = "";
        
        // walk over all modules:
        int l_numberOfElements = m_ModulesList.getModel().getSize();
        
        for(int i = 0; i < l_numberOfElements; i++){
        	ModuleElement e = (ModuleElement) m_ModulesList.getModel().getElementAt(i);
            
            // if they are enabled, add the class names to the result
            if(! e.isEnabled()){
                l_result += e.getName() + " ";
            }
        }
        
        // ok, done:
        return l_result;
    }
    
    //---------------------------------------------------------------------------
    /**
     * Method is part of the Relocalizable interface. The method does everything
     * required to reflect changes of active Locale
     */
//---------------------------------------------------------------------------
    
    public void relocalize() {
       
       super.relocalize();
       
       m_CommentLabel.setText(Translatrix.getTranslationString("ModulesManagerPlugin.Comment"));
       m_EnableButton.setText(Translatrix.getTranslationString("ModulesManagerPlugin.enable"));
       m_DisableButton.setText(Translatrix.getTranslationString("ModulesManagerPlugin.disable"));
       
       m_ModulesLabel.setText(Translatrix.getTranslationString("ModulesManagerPlugin.availableModules"));
       setLabel(Translatrix.getTranslationString("ModulesManagerPlugin.ModuleManager"));
    }
    
    
    public class ModuleFormatterJListRenderer extends JLabel implements
    ListCellRenderer {

private static final long serialVersionUID = 1L;

/**
 * builds a new DefaultComboboxRenderer
 */
public ModuleFormatterJListRenderer() {
    setOpaque(true);
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
}

            /*
             * (non-Javadoc)
             *
             * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList,
             *      java.lang.Object, int, boolean, boolean)
             */
public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }
    try {
        String l_description = ((ModuleElement)value).getName();
      
        this.setText(l_description.substring(l_description.lastIndexOf(".")+1));
     
        if(((ModuleElement)value).isEnabled()){
            this.setIcon(GECAMedModule.getSmallIcon(GECAMedModule.OK));
        } else {
            this.setIcon(GECAMedModule.getSmallIcon(GECAMedModule.CANCEL));
        }
    } catch (Exception e) {
    	logger.log(Level.WARN, "rendering modulemanagerplugin failed" ,e);
    }
    return this;
}

}
  
    public class ModuleElement {
    	
    	private String name;
    	private boolean enabled;
    	
    	public ModuleElement(String name, boolean enabled) {
    		this.name = name;
    		this.enabled = enabled;
    	}
    	
    	public String getName() {
    		return name;
    	}
    	
    	public boolean isEnabled() {
    		return enabled;
    	}
    	
    	public void setEnabled(boolean enabled) {
    		this.enabled = enabled;
    	}
    	
    }
    
    
}

