package charactermanaj.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Locale;


/**
 * リソースからローカライズされたテキストを取得する.<br>
 * @author seraphy
 *
 */
public class LocalizedResourceTextLoader extends ResourceLoader {

	private static final LocalizedResourceTextLoader inst = new LocalizedResourceTextLoader();
	
	private LocalizedResourceTextLoader() {
		super();
	}
	
	public static LocalizedResourceTextLoader getInstance() {
		return inst;
	}
	
	/**
	 * リソース名を指定して、テキストファイルを読み込んで、その文字列を返す.<br>
	 * リソースは現在のデフォルトロケールを優先で検索されます.<br>
	 * ファイルエンコーディングを引数csで指定する.<br>
	 * @param name リソース名
	 * @param cs ファイルのエンコーディング
	 * @return ファイルの内容(テキスト)
	 */
	public String getText(String name, Charset cs) {
		return getText(name, cs, Locale.getDefault());
	}

	public String getText(String name, Charset cs, Locale locale) {
		if (name == null || name.length() == 0 || cs == null || locale == null) {
			throw new IllegalArgumentException();
		}
		
		String language = locale.getLanguage();
		String country = locale.getCountry();
		String variant = locale.getVariant();

		int extpos = name.lastIndexOf(".");
		int folderpos = name.lastIndexOf("/");
		
		String basename;
		String ext;
		if (folderpos > extpos) {
			basename = name;
			ext = "";
		} else {
			basename = name.substring(0, extpos);
			ext = name.substring(extpos);
		}
		
		String[] resourceNamesStr = {
			basename + "_" + language + "_" + country + "_" + variant + ext,
			basename + "_" + language + "_" + country + ext,
			basename + "_" + language + ext,
			basename + ext,
		};

		ResourceNames resourceNames = new ResourceNames(resourceNamesStr);
		String text = loadText(resourceNames, cs);
		if (text == null) {
			throw new RuntimeException("resource not found: " + resourceNames);
		}
		return text;
	}

	protected String loadText(ResourceNames resourceNames, Charset cs) {
		if (resourceNames == null || cs == null) {
			throw new IllegalArgumentException();
		}

		for (String resourceName : resourceNames) {
			URL url = getResource(resourceName);
			if (url == null) {
				continue;
			}
			StringBuilder buf = new StringBuilder();
			try {
				InputStream is = url.openStream();
				try {
					BufferedReader rd = new BufferedReader(new InputStreamReader(is, cs));
					int ch;
					while ((ch = rd.read()) != -1) {
						buf.append((char) ch);
					}
				} finally {
					is.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("resource loading error: " + ex, ex);
			}
			return buf.toString();
		}
		return null;
	}
}
