package system.util;

import system.util.*;
import java.io.*;
import java.net.*;
import java.sql.*;
/**
 * This thread saves the wr Cache Table in the 'wr' DB
 * @author: Nikolai Rangelov
 */
public class wrSaver extends Thread 
{
	private static wrCachTableField CachTable[] = null;
 	private static short MaxFields = 0;
 	private static byte  DownloadMinutes = 0;
	private static Connection dbConnect = null;
	private static LogPrinter wrLog = null;
	public static volatile byte State = Constants.NOT_INITED;
	public static volatile boolean IsSaving = false;
/**
 * wrSaver constructor. Loads global parameters for the Thread and sets its state.
 */
public wrSaver(wrCachTableField CT[], short MF, LogPrinter SwrLog) {
	super();
	State = Constants.NOT_INITED;
	IsSaving = false;
	CachTable = null;
	MaxFields = 0;
	DownloadMinutes = 0;
	dbConnect = null;
	wrLog = null;
	wrLog = SwrLog;
	if (wrLog == null) {
		State = Constants.LOG_ERROR;
	} else {
		try {
			DownloadMinutes = wrConf.cb_Minutes_to_Download;
			MaxFields = MF;
			if (MaxFields < 1 || DownloadMinutes < 1) {
				State = Constants.INIT_ERROR;
				wrLog.log("wrSaver (constructor) : Error in sent max fields or download minutes parameters.", LogPrinter.ERROR);
				wrLog.flush();
			} else {
				CachTable = CT;
				if (CachTable == null) {
					State = Constants.CACHE_ERROR;
					wrLog.log("wrSaver (constructor) : Error in sent Cache Table pointer - null.", LogPrinter.ERROR);
					wrLog.flush();
				} else {
					if (!wrSaverdbConnect()) {
						wrLog.log("wrSaver (constructor) : Error in getting db connection.", LogPrinter.ERROR);
						wrLog.flush();
						State = Constants.CONN_ERROR;
					} else {
						State = Constants.READY;
					}
				}
			}
		} catch (Exception e) {
			wrLog.log("wrSaver (constructor) : Exception during init. Par. are log - " + wrLog + ", MaxFields - " + MaxFields + ", Cache - " + CachTable + ", dbConn - " + dbConnect, LogPrinter.ERROR);
			wrLog.flush();
			State = Constants.INIT_ERROR;
		}
	}
}
/**
 * This is the main function of the thread that controls it. Thread sleeps for 'DownloadMinutes' minutes and <br>
 * then saves the Cache Table in the DB by calling UpdateWr() function.
 */
public void run() {
	wrLog.log("wrSaver (run) : wrSaver thread started.", LogPrinter.INFO);
	wrLog.flush();
	if (State == Constants.READY) {
		while (true) {
			try {
				yield();
				sleep(DownloadMinutes * 60000);
			} catch (InterruptedException e) {
				wrLog.log("wrSaver (run) : InterruptedException during sleeping.", LogPrinter.ERROR);
				wrLog.flush();
				yield();
			}
			IsSaving = true;
			if (!SaveWrCache()) {
				wrLog.log("wrSaver (run) : Error during downloading cache table. Cache Table not downloaded to the end.", LogPrinter.ERROR);
				wrLog.flush();
			}
			IsSaving = false;
			yield();
		}
	} else {
		wrLog.log("rwSaver (run) : Error in Save Thread state - " + State, LogPrinter.ERROR);
		wrLog.flush();
		wrSaverdbDisConnect();
		return;
	}
}
/**
 * Saves the wr Cache Table in the 'wr' DB
 *	       <br> true  - if the method succeed 
 * 		   <br> false - if the method failed 
 */
public boolean SaveWrCache() {
	short Count = 0;
	String SQLStat = null;
	wrCachTableField Field = null;
	boolean HasSaved = false;
	for (Count = 1; Count <= MaxFields; Count++) {
		Field = CachTable[Count];
		yield();
		if (Field.cf_wrKey != Constants.No_Key)
			if (Field.cf_wrCounts != 0) {
				do {
					synchronized (Field) {
						if (!Field.cf_NA) {
							Field.cf_NA = true;
							break;
						}
					} // sinchronized	
					try {
						yield();
						Thread.sleep(20);
					} catch (Exception e) {
						wrLog.log("wrSaver (UpdateWr) : Error on Getting NA!", LogPrinter.ERROR);
						wrLog.flush();
						return false;
					}
				} while (true);
				if (Field.cf_wrKey != Constants.No_Key)
					if (Field.cf_wrCounts != 0) {
						if (!wrWriteInDB(Field)) {
							Field.cf_NA = false;
							wrLog.log("wrSaver (UpdateWr) : Error on dounloading rw : wrKey - " + Field.cf_wrKey + ", wrString - " + Field.cf_wrString + ", langKey - " + Field.cf_langKey + ", wrCounts - " + Field.cf_wrCounts + ", wrLastCount - " + Field.cf_wrLastCount, LogPrinter.ERROR);
							wrLog.flush();						
							return false;
						}						
						Field.cf_wrCounts = 0;
						HasSaved = true;
					}
				Field.cf_NA = false;
			} //if
	} //for
	yield();
	if (HasSaved)
		wrLog.log("wrSaver (UpdateWr) : wrCache Table downloaded.", LogPrinter.INFO);
	else
		wrLog.log("wrSaver (UpdateWr) : wrCache Table had already been downloaded.", LogPrinter.INFO);
	wrLog.flush();		
	return true;
}
/**
 * This method connects the wrSaver 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 wrSaverdbConnect() {
	try {
		Class.forName(wrConf.db_Drivers).newInstance();
		wrLog.log("wrSaver (wrSaverdbConnect) : Got a driver to " + dbFields.db_wrServerDB + " db.", LogPrinter.INFO);
	} catch (Exception E) {
		wrLog.log("wrSaver (wrSaverdbConnect) : Unable to load a driver to " + dbFields.db_wrServerDB + " db. Exception : " + E, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	dbConnect = null;
	try {
		dbConnect = DriverManager.getConnection(wrConf.db_host + dbFields.db_wrServerDB, wrConf.db_user, wrConf.db_password);
		wrLog.log("wrSaver (wrSaverdbConnect) : Conection to " + dbFields.db_wrServerDB + " db Established.", LogPrinter.INFO);
		if (dbConnect == null || dbConnect.isClosed()) {
			wrLog.flush();
			return false;
		}
		wrLog.flush();
		return true;
	} catch (SQLException E) {
		wrLog.log("wrSaver (wrSaverdbConnect) : SQLException in getting Connection to " + dbFields.db_wrServerDB + " db.\n" + E, LogPrinter.ERROR);
		wrLog.log("wrSaver (wrSaverdbConnect) : SQLException: " + E.getMessage(), LogPrinter.ERROR);
		wrLog.log("wrSaver (wrSaverdbConnect) : SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * This method disconnects the wrSaver from 'wr' DB softly. If there is error during disconneting procedure 
 * <br> the connection is disconnected hard way (equals null).
 */

public void wrSaverdbDisConnect() {
	try {
		if (dbConnect != null) {
			dbConnect.close();
			wrLog.log("wrSaver (wrSaverdbDisConnect) : " + dbFields.db_wrServerDB + " db closed.", LogPrinter.INFO);
			wrLog.flush();
			dbConnect = null;
		}
		return;
	} catch (Exception e) {
		wrLog.log("wrSaver (wrSaverdbDisConnect) : Cannot close the " + dbFields.db_wrServerDB + " db \n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return;
	}
}
/**
 * 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 (dbConnect == 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 Date(Field.cf_wrLastCount) + "' WHERE " + dbFields.db_wrKey + " = " + String.valueOf(Field.cf_wrKey);
			Statement stmt = dbConnect.createStatement();
			int result = stmt.executeUpdate(SQLStat);
			if (result == 1) {
				wrLog.log("wrSaver (wrWriteInDB) : wrString = " + Field.cf_wrString + " updated in the DB.", LogPrinter.DEBUG);
			} else {
				wrLog.log("wrSaver (wrWriteInDB) : Res from updating = " + result + ", wrKey = " + Field.cf_wrKey + ", wrCounts = " + Field.cf_wrCounts + ", wrString :" + Field.cf_wrString + ": not updated.", LogPrinter.ERROR);
			}
			stmt.close();
		}
		return true;
	} catch (SQLException e) {
		try {
			if (dbConnect == null || dbConnect.isClosed()) {
				if (!wrSaverdbConnect()) {
					wrLog.log("wrSaver (wrWriteInDB) : wrdbConnect() failure.", LogPrinter.ERROR);
					wrLog.flush();
					yield();
					return false;
				}
				wrLog.log("wrSaver (wrWriteInDB) : Reconnection to db is done.", LogPrinter.INFO);
				wrLog.flush();
				return wrWriteInDB(Field);
			} else {
				wrLog.log("wrSaver (wrWriteInDB) : SQL Statement error - " + SQLStat + "\n" + e, LogPrinter.ERROR);
				wrLog.flush();
				yield();
				return false;
			}
		} catch (Exception ex) {
			wrLog.log("wrServer (wrWriteInDB) : Exception in re-connect: " + ex, LogPrinter.ERROR);
			wrLog.flush();
			yield();
			return false;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrSaver (wrWriteInDB) : error format " + SQLStat, LogPrinter.ERROR);
		wrLog.flush();
		yield();
		return false;
	} catch (Exception e) {
		wrLog.log("wrSaver (wrWriteInDB) : Exception " + SQLStat, LogPrinter.ERROR);
		wrLog.flush();
		yield();
		return false;
	}
}
}

