package system.util;

import java.io.*;
import java.net.*;
import java.sql.*;
import system.util.*;

/**
 * This class creates and control wr Cache Table. It also creates and start Save Thread 
 * @author: Nikolai Rangelov
 */

// IMPORTANT : Masivite rabotiat v obhvata na short chislata!!!
public class wrCacher {
	private static short MaxFields = 0;
	private static volatile short FieldsInUse = 0;
	private static byte CleaningFactor = 0;
	private static wrCachTableField wrCachTable[] = null;
	private static short IndexesOf[][] = null;
	private static short Numbers[] = null;
	private static short Others[] = null;
	private static int AllUsedCounts = 0;
	private static float AllAvrUsedCounts = 0;
	private static long InitTime = 0; // The time when the CTFs are inited
	private static long AllLastCleared = 0; // The time when the CTFs are last cleared.
	private static wrSaver SaveThread = null;
	private static Connection dbConnection = null;
	private static boolean Cleaning = false; // Shows if CachTable is clearing at the moment
	private static LogPrinter wrLog = null;
	private static Object SynchroRegistering = null;
	public static volatile byte State = Constants.NOT_INITED;

/**
 * wrCacher constructor. Here are loaded the global parameters for the wrCacher and started the
 * <br>save thread that periodically saves the Cache Table.
 */
public wrCacher(LogPrinter SwrLog) {
	State = Constants.NOT_INITED;
	SynchroRegistering = null;
	SynchroRegistering = new Object();
	AllAvrUsedCounts = 0;
	FieldsInUse = 0;
	AllUsedCounts = 0;
	Cleaning = false;
	CleaningFactor = 0;
	dbConnection = null;
	InitTime = 0;
	MaxFields = 0;
	wrLog = null;
	wrLog = SwrLog;
	if (wrLog == null) {
		State = Constants.LOG_ERROR;
	} else {
		try {
			MaxFields = wrConf.csh_MaxCachFieldsInWR;
			CleaningFactor = wrConf.cb_CleaningFactor;
			if (MaxFields < 1 || CleaningFactor < 1) {
				wrLog.log("wrCacher (constructor) : Error in saved csh_MaxCachFieldsInWR or cb_CleaningFactor parameter.", LogPrinter.ERROR);
				wrLog.flush();
				State = Constants.INIT_ERROR;
			} else {
				InitTime = System.currentTimeMillis() / 1000;
				AllLastCleared = InitTime;
				wrCachTable = new wrCachTableField[MaxFields + 1]; // ...ds + 1 because CachTable[0] is not used.
				for (int i = 0; i <= MaxFields; i++)
					wrCachTable[i] = new wrCachTableField();
				IndexesOf = new short[26][MaxFields];
				Numbers = new short[MaxFields];
				Others = new short[MaxFields];
				if (!wrCacherdbConnect()) {
					wrLog.log("wrCacher (constructor) : Error in getting db connection. Change properties.", LogPrinter.ERROR);
					wrLog.flush();
					State = Constants.CONN_ERROR;
				} else {
					SaveThread = new wrSaver(wrCachTable, MaxFields, wrLog);
					SaveThread.start();
					if (SaveThread.State == Constants.READY) {
						wrLog.log("wrCacher (constructor) : Save Thread started. wr Cache is ready to work.", LogPrinter.INFO);
						wrLog.flush();
						State = Constants.READY;
					} else {
						wrLog.log("wrCacher (constructor) : Error in starting Save Thread. Change properties. wr Cache is not ready to work.", LogPrinter.ERROR);
						wrLog.flush();
						State = Constants.SAVE_THREAD_ERROR;
					}
				}
			}
		} catch (Exception e) {
			wrLog.log("wrCacher (constructor) : Exception during init. MaxFields - " + MaxFields + ", ClearingFactor - " + CleaningFactor + ", InitTime - " + InitTime + ", wrCachTable - " + wrCachTable + ", dbConnection - " + dbConnection + ", SaveThread - " + SaveThread, LogPrinter.ERROR);
			wrLog.flush();
			State = Constants.INIT_ERROR;
		}
	}
}
/**
 * The function adds Cache Table indes number to index arrays.
 * @return boolean
 * @param wrChar char - the first sign of the wrString
 * @param Index short - the index in the cache table
 */
private boolean AddIndex(char wrChar, short Index) {
	short Count = 0;
	try {
		if (wrChar >= 'a' && wrChar <= 'z') {
			int First = ((short) (wrChar)) - ((short) ('a'));
			for (Count = 0; Count < MaxFields; Count++)
				if (IndexesOf[First][Count] == Constants.Zero_Key) {
					IndexesOf[First][Count] = Index;
					return true;
				}
		} else
			if (wrChar >= '0' && wrChar <= '9') {
				for (Count = 0; Count < MaxFields; Count++)
					if (Numbers[Count] == Constants.Zero_Key) {
						Numbers[Count] = Index;
						return true;
					}
			} else {
				for (Count = 0; Count < MaxFields; Count++)
					if (Others[Count] == Constants.Zero_Key) {
						Others[Count] = Index;
						return true;
					}
			}
	} catch (Exception e) {
		wrLog.log("wrCacher (AddIndex) : Exception - " + e, LogPrinter.ERROR);
		wrLog.flush();
	}
	return false;
}
/**
 * Destroys the Save thread and the Cache. It frees all resources allocated by the cacher
 */
public void destroy() {
	try {
		for (int i = 0; i < 3; i++) {
			if (!SaveThread.IsSaving) {
				break;
			} else
				Thread.sleep(1000);
		}
		SaveThread.suspend();
		SaveCache();
		SaveThread.wrSaverdbDisConnect();
		SaveThread.stop();
		wrLog.log("wrCacher (destoy): Save Thread stoped.", LogPrinter.INFO);
	} catch (Exception t) {
		wrLog.log("wrCacher (destoy): Exception on stopping Save Thread - " + t, LogPrinter.ERROR);
		wrLog.flush();
	}
	wrLog.log("\n\n wrCacher : Just before destroying wrCachTable it is : \n", LogPrinter.DEBUG);
	for (int i = 1; i <= MaxFields; i++)
		if (wrCachTable[i].cf_wrKey != Constants.No_Key) {
			wrLog.log("	Cell : " + i + " | " + wrCachTable[i].cf_wrKey + " | " + wrCachTable[i].cf_wrString + " | " + wrCachTable[i].cf_wrCounts + " | " + wrCachTable[i].cf_langKey + " | " + wrCachTable[i].cf_wrLastCount + " | | " + wrCachTable[i].cf_NA + " | " + wrCachTable[i].cf_UsedCounts + " | " + wrCachTable[i].cf_AvrUsedCounts + " | " + wrCachTable[i].cf_Loaded + " ||", LogPrinter.DEBUG);
		}
	wrCacherdbDisConnect();
	wrCachTable = null;
	wrLog.log("wrCacher (destoy): system wr Cache Table destroyed.", LogPrinter.INFO);
	SaveThread = null;
	System.gc();
	Thread.yield();
}
/**
 * The function removes Cache Table indes number from index arrays.
 * @return boolean
 * @param wrChar char - the first sign of the wrString
 * @param Index short - the index in the cache table
 */
private boolean RemoveIndex(char wrChar, int Index) {
	short Count = 0;
	try {
		if (wrChar >= 'a' && wrChar <= 'z') {
			int First = ((int) (wrChar)) - ((int) ('a'));
			for (Count = 0; Count < MaxFields; Count++)
				if (IndexesOf[First][Count] == Index) {
					IndexesOf[First][Count] = Constants.Zero_Key;
					return true;
				}
		} else
			if (wrChar >= '0' && wrChar <= '9') {
				for (Count = 0; Count < MaxFields; Count++)
					if (Numbers[Count] == Index) {
						Numbers[Count] = Constants.Zero_Key;
						return true;
					}
			} else {
				for (Count = 0; Count < MaxFields; Count++)
					if (Others[Count] == Index) {
						Others[Count] = Constants.Zero_Key;
						return true;
					}
			}
	} catch (Exception e) {
		wrLog.log("wrCacher (RemoveIndex) : Exception : " + e, LogPrinter.ERROR);
		wrLog.flush();
	}
	return false;
}
/**
 * Saves the cache using the SaveThread's method.
 * @return boolean
 */
public boolean SaveCache() {
	return SaveThread.SaveWrCache();
}
/**
 * This method connects the wrCacher to 'wr' DB
 * @return boolean 
 *	       <br> true  - if the method succeed (we have connection)
 * 		   <br> false - if the method failed (we don't have connection)
 */
private boolean wrCacherdbConnect() {
	try {
		Class.forName(rwConf.db_Drivers).newInstance();
		wrLog.log("wrCacher (wrCacherdbConnect) : Got a driver to " + dbFields.db_wrServerDB + " db", LogPrinter.INFO);
	} catch (Exception E) {
		wrLog.log("wrCacher (wrCacherdbConnect) : Unable to load a driver to " + dbFields.db_wrServerDB + " db. Exception : " + E, LogPrinter.ERROR);
		wrLog.flush();		
		return false;
	}
	dbConnection = null;
	try {
		dbConnection = DriverManager.getConnection(wrConf.db_host + dbFields.db_wrServerDB, wrConf.db_user, wrConf.db_password);
		wrLog.log("wrCacher (wrCacherdbConnect) : Conection to " + dbFields.db_wrServerDB + " db Established.", LogPrinter.INFO);
		if (dbConnection == null || dbConnection.isClosed()) {
			wrLog.flush();					
			return false;
		}
		wrLog.flush();				
		return true;		
	} catch (SQLException E) {
		wrLog.log("wrCacher (wrCacherdbConnect) : SQLException in getting Connection to " + dbFields.db_wrServerDB + " db : " + E, LogPrinter.ERROR);
		wrLog.log("wrCacher (wrCacherdbConnect) : SQLException: " + E.getMessage(), LogPrinter.ERROR);
		wrLog.log("wrCacher (wrCacherdbConnect) : SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
		wrLog.flush();				
		return false;
	}
}
/**
 * This method disconnects the wrCacher from 'wr' DB softly. If there is error during 
 * <br> disconneting procedure the connection is disconnected hard way (equals null).
 */
private void wrCacherdbDisConnect() {
	try {
		if (dbConnection != null) {
			dbConnection.close();
			wrLog.log("wrCacher (wrCacherdbDisConnect) : " + dbFields.db_wrServerDB + " db closed.", LogPrinter.INFO);
			wrLog.flush();
			dbConnection = null;
		}
		return;
	} catch (Exception e) {
		wrLog.log("wrCacher (wrCacherdbDisConnect) : Cannot close the " + dbFields.db_wrServerDB + " db \n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return;
	}
}
/**
 * Cleans the Cache Table when it is full. The criteria is the average used count for the whole system and <br>
 * a percetage average used count for the specified Cache Table field.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
private boolean wrCleanCachFields() {
	if (State != Constants.READY) {
		wrLog.log("wrCacher (wrCleanCachFields) : Error in Thread State - " + State, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	AllAvrUsedCounts = 0;
	String SQLStat = null;
	wrCachTableField Field = null;
	long TimeNow = (System.currentTimeMillis() / 1000) + 1; //It is + 1 because it always will be 1 sec. > InitTime or AllLastCleared
	// int TempFactor = CleaningFactor;	
	wrLog.log("\n\nwrCacher (wrCleanCachFields) : Begin Cleaning ...", LogPrinter.DEBUG);	
	for (int Count = 1; Count <= MaxFields; Count++) {
		Field = wrCachTable[Count];
		do {
			synchronized (Field) {
				if (!Field.cf_NA) {
					Field.cf_NA = true;
					break;
				}
			} // sinchronized	
			try {
				Thread.sleep(20);
			} catch (Exception e) {
				wrLog.log("wrCacher (wrCleanCachFields) : Error on waiting for calculation of AvrUC in wrCleanCache!", LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		} while (true);
		try {
			Field.cf_AvrUsedCounts = (((float) (AllLastCleared - Field.cf_Loaded)) * Field.cf_AvrUsedCounts + (float) Field.cf_UsedCounts) / ((float) (TimeNow - Field.cf_Loaded));
			Field.cf_UsedCounts = 0;
			Field.cf_NA = false;
			AllAvrUsedCounts += Field.cf_AvrUsedCounts;
			wrLog.log("wrCacher (wrCleanCachFields) : Cell : " + Count + " | wrKey = " + Field.cf_wrKey + " | UC = " + Field.cf_UsedCounts + " | AvrUC = " + Field.cf_AvrUsedCounts + " | L = " + Field.cf_Loaded, LogPrinter.DEBUG_2);
		} catch (Exception e) {
			Field.cf_NA = false;
			wrLog.log("wrCacher (wrCleanCachFields) : Error in recouculation of the field - " + Count + " |wrKey=" + Field.cf_wrKey + "|UC=" + Field.cf_UsedCounts + "|AvrUC=" + Field.cf_AvrUsedCounts + "|L=" + Field.cf_Loaded + "|NA=" + Field.cf_NA + "\n" + e, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
	}
	AllAvrUsedCounts = AllAvrUsedCounts / MaxFields;
	AllAvrUsedCounts += 0.01;
	wrLog.log("wrCacher (wrCleanCachFields) : Befor removing TimeNow " + TimeNow + "\n AllAvrUC = " + AllAvrUsedCounts + " AllUC = " + AllUsedCounts + " and Factor =  " + CleaningFactor, LogPrinter.DEBUG_2);
	
	//do {
	// wrLog.log("--------------------- Factor will be " + TempFactor + " -------------------------" ,LogPrinter.DEBUG);	   	  
	for (int Count = 1; Count <= MaxFields; Count++) {
		Field = wrCachTable[Count];
		if (Field.cf_AvrUsedCounts <= AllAvrUsedCounts) {
			do {
				synchronized (Field) {
					if (!Field.cf_NA) {
						Field.cf_NA = true;
						break;
					}
				} // sinchronized	
				try {
					Thread.sleep(20);
				} catch (Exception e) {
					wrLog.log("wrCacher (wrCleanCachFields) : Error on waiting for calculation of AvrUC in wrCleanCache!", LogPrinter.ERROR);
					wrLog.flush();
					return false;
				}
			} while (true);
			if (!wrWriteInDB(Field)) {
				Field.cf_NA = false;
				return false;
			}
			try {
				if (!RemoveIndex(Field.cf_wrString.toLowerCase().charAt(0), Count)) {
					Field.cf_NA = false;
					wrLog.log("wrCacher (wrCleanCachFields) : Cannot remove index from one of index arrays", LogPrinter.ERROR);
					wrLog.flush();
					return false;
				}

				Field.cf_wrKey = Constants.No_Key;
				Field.cf_wrString = null;
				Field.cf_langKey = 0;
				Field.cf_wrCounts = 0;
				Field.cf_UsedCounts = 0;
				Field.cf_wrLastCount = 0;
				Field.cf_AvrUsedCounts = 0;
				Field.cf_Loaded = 0;
				Field.cf_NA = false;
				FieldsInUse--;
				wrLog.log("wrCacher (wrCleanCachFields) : wrCounts for wrKey | " + Field.cf_wrKey + " | updated and removed from CachTable", LogPrinter.DEBUG_2);
			} catch (Exception e1) {
				Field.cf_NA = false;
				wrLog.log("wrCacher (wrCleanCachFields) : Error in removing cache field - " + Count + " |wrKey=" + Field.cf_wrKey + "|UC=" + Field.cf_UsedCounts + "|AvrUC=" + Field.cf_AvrUsedCounts + "|L=" + Field.cf_Loaded + "|NA=" + Field.cf_NA + "\n" + e1, LogPrinter.ERROR);
				wrLog.flush();
			}
		} //if()
	} //for

	//  TempFactor += Constants.cb_IncreasingFactor;
	//} while (FieldsInUse == MaxFields);

	AllUsedCounts = 0;
	AllLastCleared = TimeNow;
	wrLog.log("\n\nwrCacher (wrCleanCachFields) : After removing InitTime = " + InitTime + " TimeNow " + TimeNow + "\n AllAvrUsedCounts = " + AllAvrUsedCounts + " AllUC = " + AllUsedCounts + " and Factor =  " + CleaningFactor, LogPrinter.DEBUG_2);
	for (int i = 1; i <= MaxFields; i++)
		wrLog.log("Cell : " + i + " | " + wrCachTable[i].cf_wrKey + " | " + wrCachTable[i].cf_wrCounts + " | " + wrCachTable[i].cf_langKey + " || " + wrCachTable[i].cf_NA + " | " + wrCachTable[i].cf_UsedCounts + " | " + wrCachTable[i].cf_AvrUsedCounts + " ||", LogPrinter.DEBUG_2);
	wrLog.log("\n\n", LogPrinter.DEBUG_2);
	wrLog.log("wrCacher (wrCleanCachFields) : wrCacheTable Cleaned.", LogPrinter.DEBUG);	
	return true;
}
/**
 * Registers new Cache Table field in the Cache Table.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
public boolean wrRegisterCachField(long RwrKey, String RwrString, short RlangKey, int RwrCounts) {
	if (State != Constants.READY) {
		wrLog.log("wrCacher (wrRegisterCachField) : Error in Thread State - " + State, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	if (RwrKey < 255 || RwrString == null || RlangKey < 1 || RwrCounts < 1) {
		wrLog.log("wrCacher (wrRegisterCachField) : Error in the input param! - " + RwrKey + " , " + RwrString + " , " + RlangKey + " , " + RwrCounts, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}	
	int FieldNumber = 0;
	wrCachTableField Field = null; // = new rwCachTableField();
	try {
		synchronized (SynchroRegistering) {
			if (wrSearchForString(RwrString, RlangKey) == Constants.No_Key) {
				while (FieldsInUse == MaxFields) {
					if (Cleaning == true)
						try {
						Thread.sleep(200);
					} catch (Exception e) {
						wrLog.log("wrCacher (wrRegisterCachField) : Exception on sleeping in wrRegisterCachField method!", LogPrinter.ERROR);
						wrLog.flush();
						return false;
					} else {
						Cleaning = true;
						//		System.out.println("Begin Cleaning"); //dfdfsadfgasdfgadfgadfga						
						if (!wrCleanCachFields()) {
							Cleaning = false;
							wrLog.log("wrCacher (wrRegisterCachField) : Cannot Clean the cache table.", LogPrinter.ERROR);
							wrLog.flush();
							return false;
						}
						Cleaning = false;
					}
				}
				for (FieldNumber = 1; FieldNumber <= MaxFields; FieldNumber++) {
					// Here FieldNumber must start from 1 because 0 is not a valid value in Indexes arrays
					Field = wrCachTable[FieldNumber];
					if (Field.cf_wrKey == Constants.No_Key) {
						do {
							synchronized (Field) {
								if (!Field.cf_NA) {
									Field.cf_NA = true;
									break;
								}
							} // sinchronized	
							try {
								Thread.sleep(20);
							} catch (Exception e) {
								wrLog.log("wrCacher (wrRegisterCachField) : Error on waiting in Getting NA flag in wrRegisterCacheField!", LogPrinter.ERROR);
								wrLog.flush();
								return false;
							}
						} while (true);
						++FieldsInUse;
						if (!AddIndex(RwrString.toLowerCase().charAt(0), (short) FieldNumber)) {
							--FieldsInUse;
							Field.cf_NA = false;
							wrLog.log("wrCacher (wrRegisterCachField) : Error - AddIndex() failure!", LogPrinter.ERROR);
							wrLog.flush();
							return false;
						}
						//			System.out.println("Now enter " + RrwString + " in Field : " + Field);
						//						synchronized (Field) {							
						Field.cf_wrKey = RwrKey;
						Field.cf_wrString = RwrString;
						Field.cf_langKey = RlangKey;
						Field.cf_wrCounts = RwrCounts;
						Field.cf_wrLastCount = System.currentTimeMillis();
						Field.cf_Loaded = AllLastCleared;
						Field.cf_UsedCounts = 1;
						Field.cf_AvrUsedCounts = 0;
						Field.cf_NA = false;
						//						}
						AllUsedCounts++;
						wrLog.log("wrCacher (wrRegisterCachField) registerd : " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
						return true;
					} //if(... == No_Key) 
				} // for
				wrLog.log("wrCacher (wrRegisterCachField) : " + RwrString + " has not entered in CT.", LogPrinter.ERROR);
				wrLog.flush();
				return false;
			} //if(wrSearch ...
			else {
				wrLog.log("wrCacher (wrRegisterCachField) : " + RwrString + " has already been registered.", LogPrinter.DEBUG_1);
				wrLog.flush();
				long res = wrResolveString(RwrString, RlangKey, RwrCounts);
				if (res == Constants.No_Key) {
					wrLog.log("wrCacher (wrRegisterCachField) : " + RwrString + " is tryed to be resolve second time but failed.", LogPrinter.ERROR);
					wrLog.flush();
					return false;
				} else {
					if (res == 0) {
						wrLog.log("wrCacher (wrRegisterCachField) : " + RwrString + " can not be resolved. Second Resolve failed.", LogPrinter.ERROR);
						wrLog.flush();
						return false;
					}
				}
				wrLog.log("wrCacher (wrRegisterCachField) resolved : " + RwrKey + " , " + RwrString + " , " + RlangKey + " , " + RwrCounts, LogPrinter.DEBUG);
				return true;
			}
		} //synchronized
	} catch (Exception e) {
		wrLog.log("wrCacher (wrRegisterCachField) : Exception on '" + RwrString + "' Field :" + Field + ": - " + e, LogPrinter.ERROR);
		wrLog.flush();
	}
	return false;
}
/**
 * This method updates the wrCounts Cache Table Fild and returns boolean answer whether has found 
 * <br>rw with this wrKey. If there is no such returns false.
 * @return boolean 
 */
public boolean wrResolveKey(long pwrKey, int pwrCounts) {
	if (State != Constants.READY) {
		wrLog.log("wrCacher (wrResolveString) : Error in Thread State - " + State, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	int Count = 0;
	int index = 0;
	wrCachTableField Field = null;
	try {
		char p = (char) (pwrKey % 256);
		if (p >= 'a' && p <= 'z') {
			int first = ((int) p) - ((int) 'a');
			for (Count = 0; Count < MaxFields; Count++) {
				index = IndexesOf[first][Count];
				Field = wrCachTable[index];				
				if (pwrKey == Field.cf_wrKey) {
					if (Field.cf_NA == true) {
						try {
							Thread.sleep(20);
							Count = 0;
						} catch (Exception e) {
							wrLog.log("wrCacher (wrResolveKey) : Exception on sleeping in wrResolveKey", LogPrinter.ERROR);
							wrLog.flush();
							return false;
						}
					} else {
						synchronized (Field) {
							if (!Field.cf_NA) {
								Field.cf_NA = true;
							} else {
								Count = 0;
							}
						} // sinchronized	
						Field.cf_wrCounts += pwrCounts;
						Field.cf_wrLastCount = System.currentTimeMillis();
						Field.cf_UsedCounts++;
						Field.cf_NA = false;
						AllUsedCounts++;
						wrLog.log("wrCacher (wrResolveKey) : resolved : " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
						return true;
					}
				}
			} //for
		} // if(p
		else
			if ((p >= '0') && (p <= '9')) {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Numbers[Count];
					Field = wrCachTable[index];
					if (pwrKey == Field.cf_wrKey) {
						if (Field.cf_NA == true) {
							try {
								Thread.sleep(20);
								Count = 0;
							} catch (Exception e) {
								wrLog.log("wrCacher (wrResolveKey) : Exception on sleeping in wrResolveKey", LogPrinter.DEBUG);
								wrLog.flush();
								return false;
							}
						} else {
							synchronized (Field) {
								if (!Field.cf_NA) {
									Field.cf_NA = true;
								} else {
									Count = 0;
								}
							} // sinchronized								
							Field.cf_wrCounts += pwrCounts;
							Field.cf_wrLastCount = System.currentTimeMillis();
							Field.cf_UsedCounts++;
							Field.cf_NA = false;
							AllUsedCounts++;
							wrLog.log("wrCacher (wrResolveKey) : resolved : " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
							return true;
						}
					}
				} //for     
			} else {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Others[Count];
					Field = wrCachTable[index];
					if (pwrKey == Field.cf_wrKey) {
						if (Field.cf_NA == true) {
							try {
								Thread.sleep(20);
								Count = 0;
							} catch (Exception e) {
								wrLog.log("wrCacher (wrResolveKey) : Exception on sleeping in wrResoleveKey", LogPrinter.ERROR);
								wrLog.flush();
								return false;
							}
						} else {
							synchronized (Field) {
								if (!Field.cf_NA) {
									Field.cf_NA = true;
								} else {
									Count = 0;
								}
							} // sinchronized	
							Field.cf_wrCounts += pwrCounts;
							Field.cf_wrLastCount = System.currentTimeMillis();
							Field.cf_UsedCounts++;
							Field.cf_NA = false;
							AllUsedCounts++;
							wrLog.log("wrCacher (wrResolveKey) : resolved : " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
							return true;
						}
					} //if
				} //for	  
			} //else
		return false;
	} catch (Exception e) {
		wrLog.log("wrCacher (wrResolveKey) : Exception - " + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * This method updates the wrCounts Cache Table Fild and returns wrKey on givern wrString and langKey. 
 * <br>If there is no such returns Constants.No_Key constant.
 * @return wrKey long - found wrKey or util.Constants.No_Key 
 */
public long wrResolveString(String SwrString, short SlangKey, int SwrCounts) {
	if (State != Constants.READY) {
		wrLog.log("wrCacher (wrResolveString) : Error in Thread State - " + State, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.No_Key;
	}
	int Count = 0;
	int index = 0;
	wrCachTableField Field = null;
	try {
		char p = SwrString.toLowerCase().charAt(0);
		if (p >= 'a' && p <= 'z') {
			int first = ((int) p) - ((int) 'a');
			for (Count = 0; Count < MaxFields; Count++) {
				index = IndexesOf[first][Count];
				Field = wrCachTable[index];				
				if (SwrString.equals(Field.cf_wrString) && Field.cf_langKey == SlangKey) {
					if (Field.cf_NA == true) {
						try {
							Thread.sleep(20);
							Count = 0;
						} catch (Exception e) {
							wrLog.log("wrCacher (wrResolveString) : Error on waiting in Getting NA flag in wrResolveString!", LogPrinter.ERROR);
							wrLog.flush();
							return 0;
						}
					} else {
						synchronized (Field) {
							if (!Field.cf_NA) {
								Field.cf_NA = true;
							} else {
								Count = 0;
							}
						} // sinchronized	
						Field.cf_wrCounts += SwrCounts;
						Field.cf_wrLastCount = System.currentTimeMillis();
						Field.cf_UsedCounts++;
						Field.cf_NA = false;
						AllUsedCounts++;
						wrLog.log("wrCacher (wrResolveString) : resolved - " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
						return Field.cf_wrKey;
					}
				}
			} //for
		} // if(p
		else
			if ((p >= '0') && (p <= '9')) {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Numbers[Count];
					Field = wrCachTable[index];					
					if (SwrString.equals(Field.cf_wrString) && Field.cf_langKey == SlangKey) {
						if (Field.cf_NA == true) {
							try {
								Thread.sleep(20);
								Count = 0;
							} catch (Exception e) {
								wrLog.log("wrCacher (wrResolveString) : Error on waiting in Getting NA flag in wrResolveString!", LogPrinter.ERROR);
								wrLog.flush();
								return 0;
							}
						} else {
							synchronized (Field) {
								if (!Field.cf_NA) {
									Field.cf_NA = true;
								} else {
									Count = 0;
								}
							} // sinchronized	
							Field.cf_wrCounts += SwrCounts;
							Field.cf_wrLastCount = System.currentTimeMillis();
							Field.cf_UsedCounts++;
							Field.cf_NA = false;
							AllUsedCounts++;
							wrLog.log("wrCacher (wrResolveString) : resolved - " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
							return Field.cf_wrKey;
						}
					}
				} //for     
			} else {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Others[Count];
					Field = wrCachTable[index];					
					if (SwrString.equals(Field.cf_wrString) && Field.cf_langKey == SlangKey) {
						if (Field.cf_NA == true) {
							try {
								Thread.sleep(20);
								Count = 0;
							} catch (Exception e) {
								wrLog.log("wrCacher (wrResolveString) : Error on waiting in Getting NA flag in wrResolveString!", LogPrinter.ERROR);
								wrLog.flush();
								return 0;
							}
						} else {
							synchronized (Field) {
								if (!Field.cf_NA) {
									Field.cf_NA = true;
								} else {
									Count = 0;
								}
							} // sinchronized	
							Field.cf_wrCounts += SwrCounts;
							Field.cf_wrLastCount = System.currentTimeMillis();
							Field.cf_UsedCounts++;
							Field.cf_NA = false;
							AllUsedCounts++;
							wrLog.log("wrCacher (wrResolveString) : resolved - " + Field.cf_wrKey + " , " + Field.cf_wrString + " , " + Field.cf_langKey + " , " + Field.cf_wrCounts, LogPrinter.DEBUG);
							return Field.cf_wrKey;
						}
					} //if
				} //for	  
			} //else
		return Constants.No_Key;
	} catch (Exception e) {
		wrLog.log("wrCacher (wrResolveString) : Exception - " + e, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.No_Key;
	}
}
/**
 * This method only returns wrKey on givern wrString/langKey. If there is no such returns No_Key Constant.
 * @return wrKey long
 */
public long wrSearchForString(String SwrString, int SlangKey) {
	if (State != Constants.READY) {
		wrLog.log("wrCacher (wrSearchForString) : Error in Thread State - " + State, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.No_Key;
	}
	int Count = 0;
	int index = 0;
	char p;
	try {
		p = SwrString.toLowerCase().charAt(0);
		if (p >= 'a' && p <= 'z') {
			int first = ((int) p) - ((int) 'a');
			for (Count = 0; Count < MaxFields; Count++) {
				index = IndexesOf[first][Count];
				if (SwrString.equals(wrCachTable[index].cf_wrString) && wrCachTable[index].cf_langKey == SlangKey)
					return wrCachTable[index].cf_wrKey;
			} //for
		} // if(p
		else
			if ((p >= '0') && (p <= '9')) {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Numbers[Count];
					if (SwrString.equals(wrCachTable[index].cf_wrString) && wrCachTable[index].cf_langKey == SlangKey)
						return wrCachTable[index].cf_wrKey;
				} //for     
			} else {
				for (Count = 0; Count < MaxFields; Count++) {
					index = Others[Count];
					if (SwrString.equals(wrCachTable[index].cf_wrString) && wrCachTable[index].cf_langKey == SlangKey)
						return wrCachTable[index].cf_wrKey;
				} //for	  
			}
		return Constants.No_Key;
	} catch (Exception e) {
		wrLog.log("wrCacher (wrSearchForString) : Exception - " + e, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.No_Key;
	}
}
/**
 * Updates the wrCounts and wrLastCounted properties of wr CacheTableField in the 'wr' DB.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
private boolean wrWriteInDB(wrCachTableField Field) {
	String SQLStat = null;
	try {
		if (dbConnection == null)
			throw new SQLException();
		if (Field.cf_wrCounts != 0) {
			SQLStat = "UPDATE " + Constants.wrWhichTable(Field.cf_wrString.charAt(0), Constants.No_Key) + " SET " + dbFields.db_wrCounts + " = " + dbFields.db_wrCounts + " + " + String.valueOf(Field.cf_wrCounts) + ", " + dbFields.db_wrLastCount + " = '" + new java.sql.Date(Field.cf_wrLastCount) + "' WHERE " + dbFields.db_wrKey + " = " + String.valueOf(Field.cf_wrKey);
			Statement stmt = dbConnection.createStatement();
			int result = stmt.executeUpdate(SQLStat);
			if (result == 1) {
				wrLog.log("wrCacher (wrWriteInDB) : wrString = " + Field.cf_wrString + " updated in the DB.", LogPrinter.DEBUG);
			} else {
				if (result > 1) {
					wrLog.log("wrCacher (wrWriteInDB) : Res from updating = " + result + ", wrKey = " + Field.cf_wrKey + ", wrCounts = " + Field.cf_wrCounts + ", wrString :" + Field.cf_wrString + ": is DUBLICATED.", LogPrinter.ERROR);
				} else {
					wrLog.log("wrCacher (wrWriteInDB) : Res from updating = " + result + ", wrKey = " + Field.cf_wrKey + ", wrCounts = " + Field.cf_wrCounts + ", wrString :" + Field.cf_wrString + ": not updated.", LogPrinter.ERROR);
				}
				wrLog.flush();
			}
			stmt.close();
		}
		return true;
	} catch (SQLException e) {
		try {
			if (dbConnection == null || dbConnection.isClosed()) {
				if (!wrCacherdbConnect()) {
					wrLog.log("wrCacher (wrWriteInDB) : wrdbConnect() failure.", LogPrinter.ERROR);
					wrLog.flush();
					return false;
				}
				wrLog.log("wrCacher (wrWriteInDB) : Reconnection to db done.", LogPrinter.INFO);
				wrLog.flush();
				return wrWriteInDB(Field);
			} else {
				wrLog.log("wrCacher (wrWriteInDB) : SQL Statement error - " + SQLStat + "\n" + e, LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		} catch (Exception ex) {
			wrLog.log("wrCacher (wrWriteInDB) : Exception in re-connect: " + ex, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrCacher (wrWriteInDB) : error format - " + SQLStat + "\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	} catch (Exception e) {
		wrLog.log("wrCacher (wrWriteInDB) : Exception - " + SQLStat + "\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
}

