/*******************************************************************************
 * 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.widgets;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Locale;
import java.util.Vector;

import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.GECAMedLocale;
import lu.tudor.santec.gecamed.core.ejb.session.beans.ListManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ListManagerInterface;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.i18n.Translatrix;


/**
 * JCombobox that is able to display Java Locales with their Country-Flag as Icon
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @Version
 * <br>$Log: LocaleChooser.java,v $
 * <br>Revision 1.10  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.9  2008-01-15 09:29:38  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 * <br>Revision 1.8  2007-12-06 14:46:44  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class LocaleChooser extends JComboBox implements ItemListener
{
    //~ Static fields/initializers =============================================

	private static final long serialVersionUID = 1L;
	public static final int SET_SYSTEM_LOCALE = 1;
    public static final int SET_TRANSLATRIX_LOCALE = 2;
    public static final int SET_BOTH_LOCALES = 3;

    //~ Instance fields ========================================================

    private int SetLocalesOnChange;
	private GECAMedLocale[] localeArray;

    //~ Constructors ===========================================================
    /**
     * creates a new JLocaleChooser with the wanted Locales
     * @param items the Locales
     */
    public LocaleChooser(GECAMedLocale[] items)
    {
        super(items);
        this.setRenderer(new LocaleComboBoxRenderer());
        this.addItemListener(this);
    }

    /**
     * creates a new JLocaleChooser with the wanted Locales
     * @param items the Locales
     */
    public LocaleChooser(Vector<GECAMedLocale> items)
    {
        super(items);
        this.setRenderer(new LocaleComboBoxRenderer());
        this.addItemListener(this);
    }

    /**
     * creates a new JLocaleChooser with the Translatrix.getSupportedLocales()
     */
    public LocaleChooser()
    {
    	this.loadLocales();
        this.setRenderer(new LocaleComboBoxRenderer());
        this.addItemListener(this);
    }

    /**
     * creates a new JLocaleChooser with the Translatrix.getSupportedLocales()
     */
    public LocaleChooser(int setLocalesOnChange)
    {
    	this.loadLocales();
        this.SetLocalesOnChange = setLocalesOnChange;
        this.setRenderer(new LocaleComboBoxRenderer());
        this.addItemListener(this);
    }

    //~ Methods ================================================================
    /**
     * returns the matching flag-icon for the Locales Country
     * @param l the Locale
     * @return the Flag-Icon
     */
    public static ImageIcon getFlagIcon(Locale l)
    {
        try {
	        String country = l.getCountry().toLowerCase();
	        java.net.URL imgURL = LocaleChooser.class.getResource("flags/" +
	        		country + ".png");
	        if (imgURL != null) {
	        	return new ImageIcon(imgURL);
	        }		
		} catch (Exception e) {
		}
        return new ImageIcon(LocaleChooser.class.getResource("flags/" +
                "default" + ".png"));
    }
    
    /**
     * returns the matching flag-icon for the  Country
     * @param l the Locale as String
     * @return the Flag-Icon
     */
    public static ImageIcon getFlagIcon(String l)
    {
        String country = l.toLowerCase();
        java.net.URL imgURL = LocaleChooser.class.getResource("flags/" +
                country + ".png");
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        }
        return new ImageIcon(LocaleChooser.class.getResource("flags/" +
                "default" + ".png"));
    }
    

    /**
     * Returns the selected Locale-Object
     * @return the Locale
     */
    public Locale getSelectedLocale()
    {
        return ((GECAMedLocale) this.getSelectedItem()).getLocale();
    }
    
    public GECAMedLocale getGECAMedLocale() {
    	return (GECAMedLocale) this.getSelectedItem();
    }

    /**
     * @param setLocalesOnChange
     */
    public void setSetLocalesOnChange(int setLocalesOnChange)
    {
        SetLocalesOnChange = setLocalesOnChange;
    }


    /**
     * @return
     */
    public int getSetLocalesOnChange()
    {
        return SetLocalesOnChange;
    }

    /* (non-Javadoc)
     * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
     */
    public void itemStateChanged(ItemEvent e)
    {
    	Locale l = null;
        try {
        	l = ((GECAMedLocale) e.getItem()).getLocale();
		} catch (Exception e1) {
			l = (Locale) e.getItem();
		}
    	
        if ((SetLocalesOnChange == SET_SYSTEM_LOCALE) ||
                (SetLocalesOnChange == SET_BOTH_LOCALES)) {
            Locale.setDefault(l);
        }
        if ((SetLocalesOnChange == SET_TRANSLATRIX_LOCALE) ||
                (SetLocalesOnChange == SET_BOTH_LOCALES)) {
            Translatrix.setLocale(l);
        }
    }

    public TableCellRenderer getTableCellRenderer() {
    	return new LocaleCellRenderer();
    }
    
    //~ Inner Classes ==========================================================
    /**
     * a renderer for the Locale Objects. it shows the Locale-String and the
     * coresponding Flag-Icon
     * @author Johannes Hermen johannes.hermen(at)tudor.lu Tudor/Santec
     *
     */
    public class LocaleComboBoxRenderer extends DefaultListCellRenderer
    {
        //~ Static fields/initializers =========================================

        private static final long serialVersionUID = 1L;

        //~ Methods ============================================================

        /* (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());
            }
            Locale l = null;
            try {
				l = ((GECAMedLocale) value).getLocale();
			} catch (Exception e) {
				l = (Locale) value;
			}
            try {
            	this.setText(l.getDisplayLanguage());
			} catch (Exception e) {
				this.setText("");
			}
            this.setIcon(LocaleChooser.getFlagIcon(l));
            return this;
        }
    }
    
    
    public class LocaleCellRenderer extends LineColorCellRenderer
	{

//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************
	
	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
	 */
	public Component getTableCellRendererComponent(JTable p_Table, Object
	          value, boolean p_IsSelected, boolean hasFocus, int p_Row, int p_Column) 	
		{
		super.getTableCellRendererComponent(p_Table, value, p_IsSelected, hasFocus, p_Row, p_Column);
		Locale l = null;
	    try {
			l = ((GECAMedLocale) value).getLocale();
		} catch (Exception e) {
			l = (Locale) value;
		}
	    try {
	    	this.setText(l.getDisplayLanguage());
		} catch (Exception e) {
			this.setText("");
		}
	    try {
	    	this.setIcon(LocaleChooser.getFlagIcon(l));
		} catch (Exception e) {
			this.setIcon(LocaleChooser.getFlagIcon(""));
		}
	    return this;
		} 
	}

    public void loadLocales() {
   	 // Get the type manager
		try {
			this.localeArray = ((ListManagerInterface) 
					ManagerFactory.getRemote(ListManagerBean.class)).getGECAMedLocales();
			for (int i = 0; i < localeArray.length; i++) {
				this.addItem(localeArray[i]);
			}
	    } catch (Exception e) {
		}
    }
    
}
