using System;
using System.Data.AccessClient;
using System.Data.OleDb;
using Medivators.Common;

namespace Medivators.Data.Queries
{
	public class ArchiveLogRecords 
	{
		private DateTime _date = DateTime.MinValue;
 
		public ArchiveLogRecords(DateTime ArchiveDate)
		{
			_date = ArchiveDate;
		}

		public int Insert()
		{
			int recordsEffected = 0;
			string sql = string.Empty;
			sql += " insert into ArchiveLogRecords ( [Key], RecordType, IsAlarm, LogNumber, MachineID, Station, [Text], Program, Data, [Timestamp] ) " +
				   " select LogRecords.Key, LogRecords.RecordType, LogRecords.IsAlarm, LogRecords.LogNumber, LogRecords.MachineID, LogRecords.Station, LogRecords.Text, LogRecords.Program, LogRecords.Data, LogRecords.Timestamp " +
				   " from	LogRecords " +
				   " where  LogRecords.Timestamp < " + Constants.DateDelimiter + _date + Constants.DateDelimiter +
				   " and    LogRecords.Key not in ( select [Key] from ArchiveLogRecords";
			sql = sql.Replace("\t", " ");

			AccessConnection cnn = Connection.GetInstance();
			OleDbTransaction trn = null;

			try
			{
				cnn.Open();
				trn = (OleDbTransaction)cnn.BeginTransaction();
				using (AccessCommand cmd = new AccessCommand())
				{
					cmd.Connection = cnn;
					cmd.CommandType = System.Data.CommandType.Text;
					cmd.CommandText = sql;
					cmd.Transaction = trn;
					recordsEffected = cmd.ExecuteNonQuery();
				}
			}
			catch (Exception ex)
			{
				trn.Rollback();
				ErrorHandler.GetInstance().LogException("ArchiveLogRecords Insert Error: ", ex);
				throw;
			}

			if (recordsEffected > 0)
			{
				sql = " delete from LogRecords " +
					   " where       LogRecords.Timestamp < " + Constants.DateDelimiter + _date + Constants.DateDelimiter;
				sql = sql.Replace("\t", " ");

				try
				{
					using (AccessCommand cmd = new AccessCommand())
					{
						cmd.Connection = cnn;
						cmd.CommandType = System.Data.CommandType.Text;
						cmd.CommandText = sql;
						cmd.Transaction = trn;
						recordsEffected = cmd.ExecuteNonQuery();
					}
				}
				catch (Exception ex)
				{
					trn.Rollback();
					ErrorHandler.GetInstance().LogException("ArchiveLogRecords Delete Error: ", ex);
					throw;
				}
			}
			if (recordsEffected > 0)
				trn.Commit();
			else
				trn.Rollback();
			trn.Dispose();
			return recordsEffected;
		}
	}
}
