/**
 *#########################################################################
 *
 * A component of the Gatherer application, part of the Greenstone digital
 * library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * <BR><BR>
 *
 * Author: John Thompson, Greenstone Digital Library, University of Waikato
 *
 * <BR><BR>
 *
 * Copyright (C) 1999 New Zealand Digital Library Project
 *
 * <BR><BR>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * <BR><BR>
 *
 * This program 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 General Public License for more details.
 *
 * <BR><BR>
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *########################################################################
 */
package org.greenstone.gatherer;

import java.awt.ComponentOrientation;
import javax.swing.plaf.FontUIResource;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;


/** Extends the ResourceBundle class to allow for the automatic insertion of arguments.<BR>
 * <BR>
 * Property files usable by this class have the Backus-Naur form: <BR>
 * <BR>
 * FileLine ::= Comment | Mapping <BR>
 * Comment  ::= '#' SString <BR>
 * Mapping  ::= NZString ':' SString ( Argument SString )* <BR>
 * NZString ::= ( Char | Int ) SString <BR>
 * Argument ::= '{' Int '}' <BR>
 * SString  ::= String . ['"','#',...] -> ['\"','\#',...] <BR>
 * <BR>
 * In order to add a new dictionary Locale, simply copy the existing dictionary.properties files, replace the values (Strings after the ':') with the new language specific ones being careful to maintain formatting and Gatherer placed arguments, then save the new dictionary as: <br>
 * <BR>
 * dictionary_<I>locale</I>.properties<BR>
 * <BR>
 * where locale is made of two two-letter codes seperated by an underscore. The first code is in lower-case and defines the language. The second is in upper-case and defines the country. For example the default dictionary could also correctly be called:
 * <BR>
 * dictionary_en_NZ.properties<BR>
 * @author John Thompson, Greenstone Digital Library, University of Waikato
 * @version 2.3
 */
public class Dictionary
    extends HashMap {

    /** The font used when displaying various html text. */
    static private FontUIResource font = null;
    /** A reference to remind us of the current locale. */
    static private Locale locale = null;
    /** The ResourceBundle which contains the raw key-value mappings.
	Loaded from a file named "dictionary<I>locale</I>.properties. */
    static private ResourceBundle dictionary = null;
    /** language orientation property */
    static private ComponentOrientation orientation = null;
     
	static public final int JAVA_MAJOR_VERSION;
	static {
		// Only Zulu JDK 8 or 11 are available for download, we can't download the intermediary Zulu JDK 9 or 10.
		// There are differences between JDK 8 and 11 in the way the contents of the dictionary.properties files are decoded.
		// In function Dictionary.get(),
		// - For JDK 8, we should stick to original code: initial = new String(initial_raw.getBytes("ISO-8859-1"), "UTF-8");
		// - For JDK 11, we need to leave the initial string as initial_raw, i.e. just do initial = initial_raw;
		// So we need to work out to work out the java major version number here.
		// The java version returned for Zulu JDK 8 when doing System.getProperty("java.version") is: 1.8.0_302
		// For Zulu JDK 11, the version string returned is: 11.0.28
		//initial = initial_raw; //initial = new String(initial_raw.getBytes("ISO-8859-1"), "UTF-8");
		String javaVersion = System.getProperty("java.version");
		int javaVersionNum = 1; // local variable
		String[] split = javaVersion.split("\\."); // split javaVersion string on regex indicating the period separator
		if(!split[0].equals("1")) { // javaVersion string starts with major number that is not 1, e.g. 8.xxx
			javaVersionNum = Integer.parseInt(split[0]);
		} else if(split.length == 1) { // so javaVersion major number *is* 1
			javaVersionNum = 1;
		} else { // javaVersion string starts with "1.xxx", so major number is in the xxx portion, e.g. "1.8.xx" -> major version is 8
			try {
				javaVersionNum = Integer.parseInt(split[1]);
			} catch(NumberFormatException e) {
				System.err.println("NumberFormatException while parsing the javaVersion " + javaVersion + " after period mark, " + split[1]);
				javaVersionNum = 1;
			}
		}
		JAVA_MAJOR_VERSION = javaVersionNum;
	} // end static code block
	
    public Dictionary(Locale locale, FontUIResource font)
    {
	super();

	// Initialize
	this.font = font;
	this.locale = ((locale == null) ? Locale.getDefault() : locale);
	this.dictionary = ResourceBundle.getBundle("dictionary", this.locale);
        if (this.get("Component.Orientation").equals("RTL")){
            this.orientation = ComponentOrientation.RIGHT_TO_LEFT;
        } else {
            this.orientation = ComponentOrientation.LEFT_TO_RIGHT;
        }      
        
    }
    
    /** Retrieve the two letter code of the current language we are using, according to the stored locale.
     * @return A <strong>String</strong> containing the two letter ISO639 language code.
     */
    static public String getLanguage()
    {
	return locale.getLanguage();
    }
    /** returns the Components Orientation for use with right to left languages
     * @return A <strong>ComponentOrientation</strong> with the current 
     dictionary's language orientation.
     * by  Amin Hejazi 
    */
    static public ComponentOrientation getOrientation()
    {
       return orientation;
    }
    
    static public String get(String key)
    {
	return get(key, (String[]) null);
    }

    static public String get(String key, String arg)
    {
	String[] args = new String[1];
	args[0] = arg;
	return get(key, args);
    }


    /** Used to retrieve a property value from the Locale specific ResourceBundle, based upon the key and arguments supplied. If the key cannot be found or if some other part of the call fails a default (English) error message is returned. <BR>
     * Here the get recieves a second argument which is an array of Strings used to populate argument fields, denoted {<I>n</I>}, within the value String returned.
     * @param key A <strong>String</strong> which is mapped to a initial String within the ResourceBundle.
     * @param args A <strong>String[]</strong> used to populate argument fields within the complete String.
     * @return A <strong>String</strong> which has been referenced by the key String and that either contains no argument fields, or has had the argument fields automatiically populated with formatting Strings of with argument String provided in the get call.
     */
    static public String get(String key, String[] args)
    {
	try {
	  String initial_raw = dictionary.getString(key).trim();

	    // Convert into Unicode
	    String initial = "";
	    try {
		// This "ISO-8859-1" looks out of place, but it is very important.
		// It is essential to call getBytes with an 8-bit encoding, otherwise
		// Java kindly deems some characters "undisplayable", and replaces
		// them with question marks. This is NOT good.
		
		// Only Zulu JDK 8 or 11 are available for download, we can't download the intermediary Zulu JDK 9 or 10.
		// There are differences between JDK 8 and 11 in the way the contents of the dictionary.properties files are decoded.		
		// - For JDK 8, we should stick to original code here: initial = new String(initial_raw.getBytes("ISO-8859-1"), "UTF-8");
		// - For JDK 11, we need to leave the initial string as initial_raw, i.e. just do initial = initial_raw;
		// So: do extra work for JDK 8, and retain initial_raw unmodified for JDK 11
		initial = (JAVA_MAJOR_VERSION >= 11) ? initial_raw : new String(initial_raw.getBytes("ISO-8859-1"), "UTF-8");
		//System.err.println("*** initial_raw string: " + initial_raw);
		//System.err.println("*** initial converted: " + initial);
	    }
	    catch (Exception exception) {
		DebugStream.printStackTrace(exception);
		return initial_raw;
	    }

	    // Remove any comments from the string
	    if (initial.indexOf("#") != -1) {
		initial = initial.substring(0, initial.indexOf("#"));
		initial = initial.trim();
	    }

	    // If the string contains arguments we have to insert them.
	    StringBuffer complete = new StringBuffer();

	    // While we still have initial string left.
	    while (initial.length() > 0 && initial.indexOf('{') != -1 && initial.indexOf('}') != -1) {
		// Remove preamble
		int opening = initial.indexOf('{');
		int closing = initial.indexOf('}');
		int comment_mark = initial.indexOf('-', opening); // May not exist
		if (comment_mark > closing) { // May also be detecting a later comment
		    comment_mark = -1;
		}
		complete.append(initial.substring(0, opening));
		
		// Parse arg_num
		String arg_str = null;
		if (comment_mark != -1) {
		    arg_str = initial.substring(opening + 1, comment_mark);
		}
		else {
		    arg_str = initial.substring(opening + 1, closing);
		}

		if (closing + 1 < initial.length()) {
		    initial = initial.substring(closing + 1);
		}
		else {
		    initial = "";
		}

		// Insert argument
		if (arg_str.equals("FONT")) {
		    complete.append((font != null ? font.getFontName() : "Arial"));
		}
		else {
		    int arg_num = Integer.parseInt(arg_str);
		    if (args != null && 0 <= arg_num && arg_num < args.length) {
			complete.append(args[arg_num]);
		    }
		}
	    }
	    complete.append(initial);
	    
	    return complete.toString();
	}
	catch (Exception exception) {
	    System.err.println("Missing value for key: " + key);
	    // DebugStream.printStackTrace(e);
	    return key;
	}
    }

}

