using System;
using System.Text;
using Medivators.BusinessObjects;
using Medivators.Common;
using Medivators.Common.Logging;

namespace Medivators.Data.Queries
{
	public class InsertLogRecord : AsynchronousExecute, IInsertQuery
	{
		private IDeviceRecord _record = null;
		public InsertLogRecord(IDeviceRecord Record)
		{
			_record = Record;
		}
		public void Insert()
		{
			string sql = string.Empty;
			try
			{
				string columnList = "[Key] , RecordType, IsAlarm, LogNumber, MachineID, Station, [Text], [Timestamp]";
				string valueList = Constants.DoubleQuote + ((DeviceRecord)_record).Key + Constants.DoubleQuote + ", " +
								   Constants.DoubleQuote + ((DeviceRecord)_record).RecordType.ToString() + Constants.DoubleQuote + ", " +
								   ((DeviceRecord)_record).IsAlarm.ToString() + ", " +
								   ((DeviceRecord)_record).LogNumber.ToString() + ", " +
								   ((DeviceRecord)_record).MachineID.ToString() + ", " +
								   Constants.DoubleQuote + ((DeviceRecord)_record).Station + Constants.DoubleQuote + ", " +
								   Constants.DoubleQuote + ((DeviceRecord)_record).Text + Constants.DoubleQuote + ", " +
								   Constants.DateDelimiter + ((ITimestampedDeviceRecord)_record).Timestamp + Constants.DateDelimiter; 

				
				//TODO: augment as new devices are added 
				if ( _record.GetType().Equals(typeof(DSD201EventRecord) ))
				{
					columnList += ", Program ";
					valueList += ", " +
								 ((DSD201EventRecord)_record).Program.ToString() ; 
				}
				else if ( _record.GetType().Equals(typeof(TimestampedHeaderRecord) ))
				{
					columnList += ", [Data] ";
					valueList += ", " + ((TimestampedHeaderRecord)_record).Data;
				}
				sql = "insert into LogRecords (" + columnList + ") values (" + valueList + ")";
				base.Insert(sql);
			}
			catch (Exception ex)
			{
				ErrorHandler.GetInstance().LogException("InsertLogRecord.Insert error executing SQL (" + sql + "): ", ex);
			}
		}
	}
}
