
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Collections;
import javax.swing.*;

public class LanguageComboBox extends JComboBox
{
	private File languageDirectory;

	public LanguageComboBox(File languageDirectory)
	{
		if( languageDirectory==null || !languageDirectory.isDirectory() )
			throw new IllegalArgumentException("The languages' directory object is not a real directory!");

		this.languageDirectory = languageDirectory;
		setModel(new LanguageComboBoxModel());

		Dimension size = new Dimension(50, getPreferredSize().height);

		setSize( size );
		setPreferredSize( size );

		setEditable(true); // Allow other languages than specified in list
		setSelectedItem(System.getProperty("user.language")); // Set default language

		addFocusListener( new FocusAdapter() {
			public void focusGained(FocusEvent e)
			{
				((LanguageComboBoxModel)getModel()).updateContent();
			}
		});
	}

	private class LanguageComboBoxModel extends DynamicComboBoxModel implements FilenameFilter
	{
		public LanguageComboBoxModel()
		{
			updateContent();
			if( getSize()>0 )
				selectedObject = getElementAt(0);
		}

		public void updateContent()
		{
			File[] files = languageDirectory.listFiles(this);

			model.clear();
			for( int i = 0; i<files.length; i++ )
			{
				String file_name = ((File)files[i]).getName().toLowerCase();
				int end_index = file_name.indexOf(".properties");

				model.add( file_name.substring(6, end_index) );
			}

			Collections.sort(model);
			fireContentsChanged(this, -1, -1);
		}

		public boolean accept(File dir, String name)
		{
			return name.toLowerCase().startsWith("texts_") && name.toLowerCase().endsWith(".properties");
		}
	}
}
