package com.vmx;

import java.io.*;
import java.util.Vector;
import com.one.*;
import filemanager.main;
import java.util.Enumeration;
import java.util.Hashtable;

public class Locale
{
	public static final int SELECT_DRIVE = 0, FAVOURITE = 1, OPTIONS_CMD = 2,
		EXIT_CMD = 3, DISK = 4, DISK_INFO = 5, DISK_TOTAL_SIZE = 6, KB = 7,
		BYTE = 8, DISK_AVAILABLE = 9, SELECT_CMD = 10, DELETE_CMD = 11,
		DELETE_ALL_CMD = 12, BACK_CMD = 13, RESTRICTED_FILE_NAME = 14,
		CONFIRMATION = 15, DEL_RECORD_FAVOR = 16, DEL_ALL_FAVOR = 17,					// 16, 17
		YES_CMD = 18, NO_CMD = 19, SAVE_CMD = 20, CLEAR_CMD = 21,
		ERROR = 22, NAME_EXIST_OVERWRITE_QUESTION = 23, FILE_NOT_COPIED = 24,
		FILE_NOT_MOVED = 25, FORMAT_NOT_SUPP = 26, OPEN_CMD = 27,
		INSERT_CMD = 28, PROPERTY_CMD = 29, RENAME_CMD = 30, COPY_CMD = 31,
		MOVE_CMD = 32, NEW_FOLDER_CMD = 33, NEW_FILE_CMD = 34,
		TO_FAVOUR_CMD = 35, DISK_INFO_CMD = 36, PREF_ESCAPED_STRINGS = 37,
		PREFERENCES_CMD = 38, HELP_CMD = 39, OK_CMD = 40, CANCEL_CMD = 41,
		SELECT_PASTE_IN_FOLDER = 42, INFORMATION = 43, FOLDER_NAME = 44,
		FILE_NAME = 45, SIZE = 46, ATTR = 47, LAST_MODIF = 48, RENAME = 49,
		NAME = 50, NAME_EXIST_SELECT_ANOTHER = 51, FILE_READ_ONLY = 52,
		NOT_RENAMED = 53, PREF_SHOW_HIDDEN_FILES = 54, PREF_VISUAL = 55,
		PREF_BROWSE = 56, PREF_USE_FULL_MENU = 57, ROTATE_BY = 58,
		PREF_SHOW_ERRORS = 59, CREATE_NEW_FOLDER = 60, CREATE_NEW_FILE = 61,
		NOT_CREATE_NEW_FOLDER = 62, WAIT_PLEASE = 63, WAIT = 64,
		SEARCH_CURRENT_FOLDER = 65, SEARCH_CURRENT_DISK = 66, SEARCH_ALL_DISKS = 67,
		IMAGEVIEW_SCALED = 68, ATTENTION = 69, SOURCE_FILE_READONLY_BE_COPIED = 70,
		DEL_SELECTED_FILE = 71, DEL_MARKED_FILES = 72, FOLDER_DELETED = 73,
		FOLDER_NOT_EMPTY = 74, FILE_DELETED = 75, FILE_NOT_DELETED = 76,
		LICENSE_AGR = 77, FILE_TYPE = 78, FILE_NOT_SAVED_EXIT = 79,
		SAVED = 80, BUFFER = 81, FIRST_COPY_NAME = 82, NEXT_COPY_NAME = 83,
		OPERATION_OK = 84, FILE = 85, FILE_NOT_SAVED = 86, GB = 87, MARK_CMD = 88,
		MARK_ALL_CMD = 89, DEMARK_ALL_CMD = 90, PREF_OPEN_NOT_SUPP = 91,
		MENU_LIST_SORT = 92, PREF_SCREEN_TRANSFORM = 93, NEED_RESTART = 94,
		EXTRACT_CMD = 95, EXTRACT_ALL_CMD = 96, EXTRACT_TO = 97,
		FOLDER_IMPOSSIBLE = 98, FILES_EXTRACTED = 99, YES_FOR_ALL = 100,
		NO_FOR_ALL = 101, PREF_KEY_VIBRA_DURATION = 102, COMPRESSED_SIZE = 103,
		MENU_FILE = 104, MENU_ARCHIVE = 105, MENU_PROPERTIES = 106,
		MENU_OPERATIONS = 107, MENU_CREATE = 108, MENU_SHOW = 109,
		PREF_NO_EFFECTS = 110, CREATE_ARCHIVE = 111, COMPRESSION_LEVEL = 112,
		TAG_EDITOR = 113, ID3_SONG = 114, ID3_ARTIST = 115, ID3_ALBUM = 116,
		ID3_YEAR = 117, ID3_COMMENT = 118, ID3_TRACKNUM = 119, ID3_GENRE = 120,
		MB = 121, KEY_LEFT = 122, KEY_RIGHT = 123, KEY_UP = 124, KEY_DOWN = 125,
		KEY_LSK = 126, KEY_RSK = 127, KEY_JOY = 128, KEY_DIAL = 129,
		KEY_CANCEL = 130, PREV_SCREEN_CMD = 131, NEXT_SCREEN_CMD = 132,
		PREV_LINE_CMD = 133, NEXT_LINE_CMD = 134, HOT_KEYS = 135,
		MENU_ADDITIONAL = 136, PANELS = 137, PANEL_NUMS = 138 /*[+0..9]*/,
		FULLSCREEN_CMD = 148, KEY_NO_ACTION = 149, KEYBOARD_CONFIG_CMD = 150,
		PREF_LANG = 151, COLOR_SCHEME = 152, PREF_CHECK_FILE_ATTRIB = 153,
		PREF_ACCURATE_DIR_CHECK = 154, PREF_SORT_FILE_LIST = 155, ATTR_READ_ONLY = 156,
		ATTR_HIDDEN = 157, CONTENTS = 158, CONTENTS_PATTERN = 159, PREF_PLAYER_SETUP = 160,
		PREF_ID3_ENCODING = 161, PREF_SHOW_PLAY_PROGRESS = 162, PREF_MOD_BUF_SIZE = 163,
		DONE = 164, PREF_TEXT_SETUP = 165, PREF_SHOW_CR = 166, PREF_SHOW_LF = 167,
		PREF_ACCURATE_TAB = 168, GOTO_CMD = 169, PREF_PAGE_SCROLL = 170, PREF_KEYMAP = 171,
		INITIAL_SETUP = 172, CLOCK_MODE = 173, SWITCH = 174, NEXT_PANEL = 175,
		PREV_PANEL = 176, NEXT_FREE = 177, PREV_FREE = 178, QUICK_SWITCH = 179,
		EDIT_CMD = 180, MENU_SEARCH = 181, FONT_CMD = 182, ENCODING_CMD = 183,
		RECURSIVE_SEARCH = 184, HASH_SUM = 185, CRYPT_CMD = 186, PASSWORD = 187,
		CRYPT_USAGE = 188, SIZE_SMALL = 189, SIZE_MEDIUM = 190, SIZE_LARGE = 191,
		FONT_FACE = 192, FONT_STYLE = 193, FONT_BOLD = 194, FONT_ITALIC = 195,
		FONT_MONOSPACE = 196, FONT_PROPORTIONAL = 197, FONT_SYSTEM = 198,
		FONT_UNDERLINED = 199, PREF_SHOW_MENU_NUM = 200, PREF_SHUFFLE_PLAY = 201,
		TRANSCODE = 202, PREF_CUSTOM_COLOR_SCHEME = 203, CREATE_PLAYLIST = 204,
		SEARCH_INSIDE_ARCHIVES = 205, AUDIO = 206, VIDEO = 207,
		PATH_SAVE = 208, PATH_ABSOLUTE = 209, PATH_RELATIVE = 210,
		PREF_FRAME_CURSOR = 221, OLD_NAME = 222, NEW_NAME = 223, NO_IMAGE = 224,		// 221, 222, 223, 224
		FILTER_TYPE = 225, NAME_TEMPLATE = 226, MINIMIZE_CMD = 227, CONFIRM_SAVE = 228,		// 225
		SAVE_AS_CMD = 229, MENU_EDIT = 230, UNDO_CMD = 231, REDO_CMD = 232, FIND_CMD = 233,
		FIND_NEXT_CMD = 234, MENU_VIEW = 235, PREF_ARCHIVE_ENCODING = 236, LINE_NUMBER = 237,
		PREF_REMEMBER_PATH = 238, TEMPLATES_CMD = 239, USE_UTF_BOM = 240,
		SEARCH_EOF_QUESTION = 241, GOTO_START_CMD = 242, GOTO_END_CMD = 243, ADD_CMD = 244,
		PREF_PLAY_ALERT_SOUNDS = 245, PREF_SWAP_SOFT_KEYS = 246, IGNORE_CASE = 247,
		SORT_NONE = 248, SORT_BY_NAME = 249, SORT_BY_TYPE = 250, SORT_BY_DATE = 251, SORT_BY_SIZE = 252,
		PREF_SORT_OPTIONS = 253, SORT_REVERSE_ORDER = 254, RESTART_CMD = 255,
		PREF_MARK_MOVE_NEXT = 256, REPLACE_CMD = 257, REPLACE_ALL_CMD = 258,
		REPLACE_WITH = 259, PREF_ALTER_CLOCK_POS = 260, SEARCH_MATCHES = 261,
		EQUALIZER = 262, HZ = 263, KHZ = 264, DB = 265, PREF_USE_ACCELEROMETER = 266,
		PREF_LIGHT_CONTROL_MODE = 267, PREF_MOD_SAMPLE_RATE = 268, PREF_MOD_QUALITY = 269,
		QUALITY_LOW = 270, QUALITY_MEDIUM = 271, QUALITY_HIGH = 272, DISABLED = 273,
		ENABLED = 274, AUTOMATIC = 275, ESCAPE_CMD = 276, UNESCAPE_CMD = 277,
		BUFFER_EMPTY = 278, MODULES_CMD = 279, PACKING_FILE = 280, CHARACTER = 283,
		PREF_TEXTBOX_TITLE = 284, NORMAL = 285, TICKER = 286, UNPACKING_FILE = 289,
		MEMORY_MONITOR = 290, UPDATE_CMD = 291, FILL_CMD = 292, USED_MEMORY = 293,
		TOTAL_MEMORY = 294, PREF_MM_DELAY = 295, PREF_MM_THRESHOLD = 296, CONTAINERS = 297,
		CLOSE_CMD = 298, CLOSE_ALL_CMD = 299, WRITING_FILE = 300, PALETTE_CMD = 301,
		COLOR_SELECTOR = 302, CONTAINER_INFO = 303, PREF_LONG_SCROLL_SPEED = 304,
		INSTALLING_COLOR_SCHEME = 305, PREF_DITHER_GRADIENTS = 306, PREF_ALPHA_GRADIENTS = 307,
		PREF_TEXT_BUFFER_SIZE = 308, PREF_FULL_FILE_NAMES = 309, IN_BUFFER = 310,
		IN_FAVOURITES = 311, ENTER_CMD = 312, KEY_ASSIGNMENT = 313, USER_KEYS = 314,
		KEY_EDITOR = 315, KEY_CODE = 316, ABBREVIATION = 318, PRESS_A_KEY = 319,
		HOT_KEY_NAME = 320, HELD_KEY_NAME = 321, ROOT = 322, FILE_LIST = 323,
		BIT_BUCKET = 324, ASSIGN_CMD = 326, RESET_CMD = 327, PREF_CACHE_CODE_PAGES = 328,
		PREF_LARGE_FONT = 329, IN_FILE_LIST = 330, IN_MENU = 331, PREF_EXIT_FROM_DRIVE_LIST = 332,
		METADATA_FORMAT = 333, PREF_SHOW_META_KEYS = 334, REG_EXP_CMD = 335, RE_MATCH_MULTILINE = 336,
		RE_REPLACE_BACKREF = 337, PREF_DUPLEX_FILE_ACCESS = 338, PREF_TEMP_FILE_DIR = 341,
		COLOR_COUNT = 346, PREPROCESS = 347, QUANTIZATION = 348, ERROR_DISTRIBUTION = 349,
		MENU_KEY_REMAP = 350, KEY_NUM1 = 351, KEY_NUM0 = 360, KEY_STAR = 361, KEY_POUND = 362,
		EFFECTS_CMD = 363, TRANSPARENCY = 364, ROTATE_CMD = 365, SCALE_CMD = 366,
		ENABLE_UI_CMD = 367, PREF_UNLOAD_MODULES = 368, TEXT = 369, NAME_FORMAT_CMD = 370,
		COUNTER_START = 371, COUNTER_STEP = 372, DIGIT_CAPACITY = 373, LETTER_CASE = 374,
		CASE_UNCHANGED = 375, ALL_LOWERCASE = 376, ALL_UPPERCASE = 377, LINE_FIRST_UPPERCASE = 378,
		WORD_FIRST_UPPERCASE = 379, FONT_CONFIG = 381, FONTS_CMD = 382, INSTALLED_FONT = 383,
		FONT_PATH = 384, PREF_VIRTUALIZE_TO_RAM = 391, DEVICE_FONT = 392, MENU_FAV_MODULES = 393,
		FAV_MOD_NUMS = 394, TAB_SIZE = 404, CHAPI_CMD = 405, CHAPI_OPEN_WITH = 406, MIME_TYPES_CMD = 407,
		MIME_TYPE = 408, DEL_ALL_IN_BUFFER = 409, NO_STANDALONE_OPTIONS = 412, PASSWORDS_CMD = 413,
		PASS_FOR_LAUNCH = 414, PASS_FOR_OPTIONS = 415, PASSWORD_REQUIRED = 416, PASS_REQUEST_ON_LAUNCH = 417,
		PASS_REQUEST_ON_OPTIONS = 418, ENTER_PASSWORD = 419, INCORRECT_PASSWORD = 420,
		PREF_NEW_FILE_NAME_FORMAT = 421, PREF_ERROR_LOG_FILE = 422, PREF_USE_TEMPLATES = 423;

	public static String ABOUT_MIDLET_NAME = TextProcessor.byteArrayToString(new byte[] { 85, 110, 105, 70, 77, 32, 118 }) +
		          main.loader.getAppProperty(TextProcessor.byteArrayToString(new byte[] { 77, 73, 68, 108, 101, 116, 45, 86, 101, 114, 115, 105, 111, 110 }));
	
	public static String ABOUT_DEPLOYMENT_NUMBER = main.loader.getAppProperty(TextProcessor.byteArrayToString(new byte[] { 68, 101, 112, 108, 111, 121, 109, 101, 110, 116, 45, 78, 117, 109, 98, 101, 114 }));

	//protected static String[] Strings;
	//protected static final int STRING_COUNT = 278;

	protected static IniFile locdata;
	//protected static RecordStore locstore;

	protected static Hashtable strings = new Hashtable();

	protected static final Integer NO_OFFSET = new Integer(0);
	protected static Hashtable offset_table = new Hashtable();
	protected static Hashtable offset_patterns = new Hashtable();
	
	public static String lang;
	
	public static String[] locales = null;   // имена языков типа "ru", "en"...
	public static String[] languages = null; // названия языков (русский, english, ...)

	/**
	 * Конструктор
	 */
	public Locale()
	{
	}
	
	public static void loadLocale(String newlang) throws IOException
	{
		lang = newlang;
		strings.clear();
		
//		try
//		{
//			if(locstore != null)
//			{
//				locstore.closeRecordStore();
//			}
//
//			locstore = RecordStore.openRecordStore(AuxClass.getStoreName(12), false);
//
//			if(lang.equals(new String(locstore.getRecord(1))))
//			{
//				RecordEnumeration re = locstore.enumerateRecords(null, null, false);
//				int id;
//
//				byte[] data;
//
//				while(re.hasNextElement())
//				{
//					id = re.nextRecordId();
//
//					if(id != 1)
//					{
//						data = locstore.getRecord(id);
//						strings.put(new Integer((((int)data[0] & 0xFF) << 24) + (((int)data[1] & 0xFF) << 16) + (((int)data[2] & 0xFF) << 8) + ((int)data[3] & 0xFF)), new Integer(id));
//					}
//				}
//
//				re.destroy();
//
//				return;
//			}
//			else
//			{
//				locstore.closeRecordStore();
//				RecordStore.deleteRecordStore(AuxClass.getStoreName(12));
//			}
//		}
//		catch(RecordStoreNotFoundException rsnfe)
//		{
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}

		loadStrings("/lang/" + lang + "/strings.ini", 0);

		Enumeration keys = locdata.listKeys("Custom");
		String key, value;

		while(keys.hasMoreElements())
		{
			key = (String)keys.nextElement();
			value = locdata.getRecord("Custom", key);

			try
			{
				loadStrings(TextProcessor.replaceText(key, "%L", lang), Integer.parseInt(value));
			}
			catch(Exception x)
			{
				System.out.println(x.toString() + " while loading " + key + " at " + value);
			}
		}
		
//		try
//		{
//			locstore = RecordStore.openRecordStore(AuxClass.getStoreName(12), true);
//
//			byte[] data = lang.getBytes();
//			locstore.addRecord(data, 0, data.length);
//
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			DataOutputStream dos = new DataOutputStream(baos);
//
//			Enumeration indices = strings.keys();
//			Integer index;
//
//			while(indices.hasMoreElements())
//			{
//				index = (Integer)indices.nextElement();
//
//				dos.writeInt(index.intValue());
//				dos.write(((String)strings.get(index)).getBytes());
//
//				data = baos.toByteArray();
//				baos.reset();
//
//				strings.put(index, new Integer(locstore.addRecord(data, 0, data.length)));
//			}
//
//			dos.close();
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
	}

	public static void loadStrings(String file, int offset) throws IOException
	{
		InputStreamDecoder ini = InputStreamDecoder.getResourceDecoder(file);
		IniRecord record = null;

		//int offset = 0;

		while((record = IniRecord.getNextRecord(ini)) != null)
		{
			try
			{
//				if(record.key.startsWith("[") && record.key.endsWith("]"))
//				{
//					offset = Integer.parseInt(record.key.substring(1, record.key.length() - 1).trim());
//				}

				strings.put(new Integer(Integer.parseInt(record.key) + offset), TextProcessor.unescapeString(record.value));
			}
			catch(Exception e)
			{
				System.out.println(e.toString() + " because of " + record.key + ", " + record.value);
			}
		}

		ini.close();
	}

	public static int getOffset(Object object)
	{
		if(object == null)
		{
			return 0;
		}

		if(!(object instanceof String))
		{
			object = object.getClass().getName();
		}

		Integer offset = (Integer)offset_table.get(object);

		if(offset != null)
		{
			return offset.intValue();
		}
		else
		{
			Enumeration patterns = offset_patterns.keys();
			StringPattern pattern;

			while(patterns.hasMoreElements())
			{
				pattern = (StringPattern)patterns.nextElement();

				if(pattern.matchesWith((String)object))
				{
					offset = (Integer)offset_patterns.get(pattern);
					offset_table.put(object, offset);

					return offset.intValue();
				}
			}

			offset_table.put(object, NO_OFFSET);
			return 0;
		}
	}

	public static String getString(Object object, int index)
	{
		Integer key = new Integer(index + getOffset(object));
		Object obj = strings.get(key);

		if(obj == null)
		{
			return key.toString() + "s";
		}

		String res;

		if(obj instanceof Integer)
		{
			res = obj.toString() + "r";

//			try
//			{
//				byte[] data = locstore.getRecord(((Integer)obj).intValue());
//				res = new String(data, 4, data.length - 4);
//			}
//			catch(Exception e)
//			{
//				res = obj.toString() + "r";
//			}
		}
		else
		{
			res = (String)obj;
		}

		if(res.startsWith("#"))
		{
			res = getString(object, Integer.parseInt(res.substring(1).trim()));
		}

		if(res != obj)
		{
			strings.put(key, res);
		}

		return res;
	}
	
	public static String getString(Object object, int index, String token)
	{
		return TextProcessor.replaceText(getString(object, index), "%A", token);
	}

	public static String getString(Object object, int index, String[] tokens)
	{
		String res = getString(object, index);

		for(int i = 0; i < tokens.length; i++)
		{
			res = TextProcessor.replaceText(res, "%" + (char)('A' + i), tokens[i]);
		}

		return res;
	}
	
	/**
	 * Получить поток с текстом about'а
	 */	
	public static InputStream getAboutStream()
	{
		try
		{
			return AuxClass.getResourceAsStream("/lang/" + lang + "/about.txt");
		}
		catch(Exception e)
		{
			return new ByteArrayInputStream(StringEncoder.encodeString(e.toString(), StringEncoder.ENC_UTF8));
		}
	}
	
	/**
	 * Текст лицензии
	 */
	public static String getLicenseString()
	{
		try
		{
			InputStreamDecoder isd = InputStreamDecoder.getResourceDecoder("/lang/" + lang + "/license.txt");
			
			StringBuffer s = new StringBuffer(isd.available());
			
			while(isd.available() > 0)
			{
				s.append(isd.readChar());
			}
			
			isd.close();
			
			return s.toString();
		}
		catch(Exception e)
		{
			return e.toString();
		}
	}
		
	/**
	 * Получить список доступных языков
	 */
	public static void readLocaleList() throws IOException
	{
		locdata = new IniFile("/lang/lang.ini", false);

		Enumeration keys = locdata.listKeys("List");
		String key, value;

		Vector v = new Vector();
		IniRecord record;

		while(keys.hasMoreElements())
		{
			key = (String)keys.nextElement();
			v.addElement(new IniRecord(key, locdata.getRecord("List", key)));
		}
		
		languages = new String[v.size()];
		locales = new String[v.size()];
		
		for(int i = 0; i < languages.length; i++)
		{
			record = (IniRecord)v.elementAt(i);

			locales[i] = record.key;
			languages[i] = record.value;
		}

		keys = locdata.listKeys("Offset");

		offset_table.clear();
		offset_patterns.clear();

		while(keys.hasMoreElements())
		{
			key = (String)keys.nextElement();
			value = locdata.getRecord("Offset", key);

			try
			{
				offset_table.put(key, new Integer(Integer.parseInt(value)));
				offset_patterns.put(new StringPattern(key, false), new Integer(Integer.parseInt(value)));
			}
			catch(Exception x)
			{
			}
		}
	}
}
