package de.fun2code.android.piratebox.preference;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
import de.fun2code.android.piratebox.Constants;

public class CustomI18nListPreference extends ListPreference {

	public CustomI18nListPreference(Context context) {
		super(context);
	}

	public CustomI18nListPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		String i18nDir = Constants.getInstallDir(context) + "/html/i18n";
		
		File[] i18nFiles = new File(i18nDir).listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().matches("^.*_[a-z]{2}\\.properties$");
			}
		});
		
		Arrays.sort(i18nFiles);
		
		List<CharSequence> entriesList = new ArrayList<CharSequence>();
		List<CharSequence> valuesList = new ArrayList<CharSequence>();
		
		for(File file : i18nFiles) {
			String lang = file.getName().replaceAll("^.*_([a-z]{2})\\.properties$", "$1");
			String langDisp = new Locale(lang).getDisplayLanguage(Locale.getDefault());
			
			entriesList.add(langDisp);
			valuesList.add(lang);
		}
		
		setEntries(entriesList.toArray(new CharSequence[entriesList.size()]));
		setEntryValues(valuesList.toArray(new CharSequence[valuesList.size()]));
	}

}

@@ -871,16 +871,46 @@
 );%0A%09%09%0A%09%09
+%0A%09%09if(i18nFiles != null) %7B%0A%09%09%09
 Arrays.s
@@ -927,19 +927,21 @@
 les);%0A%09%09
+%09
 %0A%09%09
+%09
 List%3CCha
@@ -996,16 +996,17 @@
 nce%3E();%0A
+%09
 %09%09List%3CC
@@ -1064,17 +1064,19 @@
 e%3E();%0A%09%09
-%0A
+%09%0A%09
 %09%09for(Fi
@@ -1097,24 +1097,25 @@
 Files) %7B%0A%09%09%09
+%09
 String lang 
@@ -1184,16 +1184,17 @@
 1%22);%0A%09%09%09
+%09
 String l
@@ -1264,20 +1264,22 @@
 ());%0A%09%09%09
+%09
 %0A%09%09%09
+%09
 entriesL
@@ -1297,16 +1297,17 @@
 gDisp);%0A
+%09
 %09%09%09value
@@ -1329,13 +1329,16 @@
 ;%0A%09%09
+%09
 %7D%0A%09%09
-%0A
+%09%0A%09
 %09%09se
@@ -1406,16 +1406,17 @@
 e()%5D));%0A
+%09
 %09%09setEnt
@@ -1482,14 +1482,110 @@
 e()%5D));%0A
+%09%09%7D%0A%09%09else %7B%0A%09%09%09setEntries(new CharSequence%5B0%5D);%0A%09%09%09setEntryValues(new CharSequence%5B0%5D);%0A%09%09%7D%0A%09%09%0A
 %09%7D%0A%0A%7D%0A

Handle null values