package system.util;

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

/**
 * This thread saves the rw Cache Table in the 'rw' DB
 * @author: Nikolai Rangelov
 */
public class rwSaver extends Thread {
	private static rwCachTableField CachTable[] = null;
	private static short MaxFields = 0;
	private static byte DownloadMinutes = 0;
	private static Connection dbConnect = null;
	private static LogPrinter rwLog = null;
	public static volatile byte State = Constants.NOT_INITED;
	public static volatile boolean IsSaving = false;
/**
 * rwSaver constructor. Loads global parameters for the Thread and sets its state.
 */
public rwSaver(rwCachTableField CT[], short MF, LogPrinter slog) {
	super();
	State = Constants.NOT_INITED;
	IsSaving = false;
	CachTable = null;
	MaxFields = 0;
	DownloadMinutes = 0;
	dbConnect = null;
	rwLog = null;
	rwLog = slog;
	if (rwLog == null) {
		State = Constants.LOG_ERROR;
	} else {
		try {
			DownloadMinutes = rwConf.cb_Minutes_to_Download;
			MaxFields = MF;
			if (MaxFields < 1 || DownloadMinutes < 1) {
				State = Constants.INIT_ERROR;
				rwLog.log("rwSaver (constructor) : Error in sent max fields or download minutes parameters.", LogPrinter.ERROR);
				rwLog.flush();
			} else {
				CachTable = CT;
				if (CachTable == null) {
					State = Constants.CACHE_ERROR;
					rwLog.log("rwSaver (constructor) : Error in sent Cache Table pointer - null.", LogPrinter.ERROR);
					rwLog.flush();
				} else {
					if (!rwSaverdbConnect()) {
						rwLog.log("rwSaver (constructor) : Error in getting db connection.", LogPrinter.ERROR);
						rwLog.flush();
						State = Constants.CONN_ERROR;
					} else {
						State = Constants.READY;
					}
				}
			}
		} catch (Exception e) {
			rwLog.log("rwSaver (constructor) : Exception during init. Par. are log - " + rwLog + ", MaxFields - " + MaxFields + ", Cache - " + CachTable + ", dbConn - " + dbConnect, LogPrinter.ERROR);
			rwLog.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 UpdateRw() function.
 */
public void run() {
	rwLog.log("rwSaver (run) : rwSaver thread started.", LogPrinter.INFO);
	rwLog.flush();
	if (State == Constants.READY) {
		while (true) {
			try {
				yield();
				sleep(DownloadMinutes * 60000);
			} catch (InterruptedException e) {
				rwLog.log("rwSaver (run) : InterruptedException during sleeping.", LogPrinter.ERROR);
				rwLog.flush();
				yield();
			}
			IsSaving = true;			
			if (!SaveRwCache()) {
				rwLog.log("rwSaver (run) : Error during downloading cache table. Cache Table not downloaded to the end.", LogPrinter.ERROR);
				rwLog.flush();
			}
			IsSaving = false;	
			yield();	
		}
	} else {
		rwLog.log("rwSaver (run) : Error in Save Thread state - " + State, LogPrinter.ERROR);
		rwLog.flush();
		rwSaverdbDisConnect();
		return;
	}
}
/**
 * This method connects the market_rwSaver to Market_rw 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 rwSaverdbConnect() {
	try {
		Class.forName(rwConf.db_Drivers).newInstance();
		rwLog.log("rwSaver (rwSaverdbConnect) : Got a driver to " + dbFields.db_rwServerDB + " db.", LogPrinter.INFO);
	} catch (Exception E) {
		rwLog.log("rwSaver (rwSaverdbConnect) : Unable to load a driver to " + dbFields.db_rwServerDB + " db. Exception : " + E, LogPrinter.ERROR);
		rwLog.flush();
		return false;
	}
	dbConnect = null;
	try {
		dbConnect = DriverManager.getConnection(rwConf.db_host + dbFields.db_rwServerDB, rwConf.db_user, rwConf.db_password);
		rwLog.log("rwSaver (rwSaverdbConnect) : Conection to " + dbFields.db_rwServerDB + " db Established.", LogPrinter.INFO);
		if (dbConnect == null || dbConnect.isClosed()) {
			rwLog.flush();
			return false;
		}
		rwLog.flush();
		return true;
	} catch (SQLException E) {
		rwLog.log("rwSaver (rwSaverdbConnect) : SQLException in getting Connection to " + dbFields.db_rwServerDB + " db.\n" + E, LogPrinter.ERROR);
		rwLog.log("rwSaver (rwSaverdbConnect) : SQLException: " + E.getMessage(), LogPrinter.ERROR);
		rwLog.log("rwSaver (rwSaverdbConnect) : SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
		rwLog.flush();
		return false;
	}
}
/**
 * This method disconnects the rwSaver from 'rw' DB softly. If there is error during 
 * <br> disconneting procedure the connection is disconnected hard way (equals null).
 */

public void rwSaverdbDisConnect() {
	try {
		if (dbConnect != null) {
			dbConnect.close();
			rwLog.log("rwSaver (rwSaverdbDisConnect) : " + dbFields.db_rwServerDB + " db closed.", LogPrinter.INFO);
			rwLog.flush();
			dbConnect = null;
		}
		return;
	} catch (Exception e) {
		rwLog.log("rwSaver (rwSaverdbDisConnect) : Cannot close the " + dbFields.db_rwServerDB + " db \n" + e, LogPrinter.ERROR);
		rwLog.flush();
		return;
	}
}
/**
 * Updates the rwCounts and rwLastCounted properties of rw CacheTableField in the 'rw' DB.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
private boolean rwWriteInDB(rwCachTableField Field) {
	String SQLStat = null;
	try {
		if (dbConnect == null)
			throw new SQLException();
		if (Field.cf_rwCounts != 0) {
			SQLStat = "UPDATE " + Constants.rwWhichTable(Field.cf_rwString.charAt(0), Constants.No_Key) + " SET " + dbFields.db_rwSumAllCounts + " = " + dbFields.db_rwSumAllCounts + " + " + String.valueOf(Field.cf_rwCounts) + " , " + dbFields.db_rwLastCount + " = '" + new java.sql.Date(System.currentTimeMillis()) + "' WHERE " + dbFields.db_rwKey + " = " + String.valueOf(Field.cf_rwKey);
			Statement stmt = dbConnect.createStatement();
			int result = stmt.executeUpdate(SQLStat);
			if (result == 1) {
				rwLog.log("rwSaver (rwWriteInDB) : rwString = " + Field.cf_rwString + " updated in the DB.", LogPrinter.DEBUG);
			} else {
				rwLog.log("rwSaver (rwWriteInDB) : Res from updating = " + result + ", rwKey = " + Field.cf_rwKey + ", rwCounts = " + Field.cf_rwCounts + ", rwString :" + Field.cf_rwString + ": - unusula result from updating.", LogPrinter.ERROR);
			}
			stmt.close();
		}
		return true;
	} catch (SQLException e) {
		try {
			if (dbConnect == null || dbConnect.isClosed()) {
				if (!rwSaverdbConnect()) {
					rwLog.log("rwSaver (rwWriteInDB) : rwdbConnect() failure.", LogPrinter.ERROR);
					rwLog.flush();
					yield();
					return false;
				}
				rwLog.log("rwSaver (rwWriteInDB) : Reconnection to db is done.", LogPrinter.INFO);
				rwLog.flush();
				return rwWriteInDB(Field);
			} else {
				rwLog.log("rwSaver (rwWriteInDB) : SQL Statement error - " + SQLStat + "\n" + e, LogPrinter.ERROR);
				rwLog.flush();
				yield();
				return false;
			}
		} catch (Exception ex) {
			rwLog.log("rwServer (rwWriteInDB) : Exception in re-connect: " + ex, LogPrinter.ERROR);
			rwLog.flush();
			yield();
			return false;
		}
	} catch (NumberFormatException e) {
		rwLog.log("rwSaver (rwWriteInDB) : error format " + SQLStat, LogPrinter.ERROR);
		rwLog.flush();
		yield();
		return false;
	} catch (Exception e) {
		rwLog.log("rwSaver (rwWriteInDB) : Exception " + SQLStat, LogPrinter.ERROR);
		rwLog.flush();
		yield();
		return false;
	}
}
/**
 * Saves the rw Cache Table in the 'rw' DB
 *	       <br> true  - if the method succeed 
 * 		   <br> false - if the method failed 
 */
public boolean SaveRwCache() {
	short Count = 0;
	String SQLStat = null;
	rwCachTableField Field = null;
	boolean HasSaved = false;
	for (Count = 1; Count <= MaxFields; Count++) {
		Field = CachTable[Count];
		yield();
		if (Field.cf_rwKey != Constants.No_Key)
			if (Field.cf_rwCounts != 0) {
				do {
					synchronized (Field) {
						if (!Field.cf_NA) {
							Field.cf_NA = true;
							break;
						}
					} // sinchronized	
					try {
						yield();
						Thread.sleep(20);
					} catch (Exception e) {
						rwLog.log("rwSaver (UpdateRw) : Error on Getting NA!", LogPrinter.ERROR);
						rwLog.flush();
						return false;
					}
				} while (true);
				if (Field.cf_rwKey != Constants.No_Key)
					if (Field.cf_rwCounts != 0) {
						if (!rwWriteInDB(Field)) {
							Field.cf_NA = false;
							rwLog.log("rwSaver (UpdateRw) : Error on dounloading rw : rwKey - " + Field.cf_rwKey + ", rwString - " + Field.cf_rwString + ", langKey - " + Field.cf_langKey + ", rwCounts - " + Field.cf_rwCounts + ", rwLastUpdate - " + Field.cf_rwLastCounts, LogPrinter.ERROR);
							rwLog.flush();						
							return false;
						}						
						Field.cf_rwCounts = 0;
						HasSaved = true;
					}
				Field.cf_NA = false;
			} //if
	} //for
	yield();
	if (HasSaved)
		rwLog.log("rwSaver (UpdateRw) : rwCache Table downloaded.", LogPrinter.INFO);
	else
		rwLog.log("rwSaver (UpdateRw) : rwCache Table had already been downloaded.", LogPrinter.INFO);
	rwLog.flush();		
	return true;
}
}

