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

namespace Medivators.Data.Queries
{
	public class UpdateLogRecord : AsynchronousExecute, IUpdateQuery
	{
		private IDeviceRecord _record = null;
		public UpdateLogRecord(IDeviceRecord Record)
		{
			_record = Record;
		}
		public void Update()
		{
			try
			{
				// note that Key is not included!
				string columnList = "RecordType, IsAlarm, LogNumber, MachineID, Station, [Text], [Timestamp]";
				string valueList = 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;
				}

				string[] columns = columnList.Split(",".ToCharArray());
				string[] values = valueList.Split(",".ToCharArray());

				string sql = string.Empty;

				for (int field = 0; field < columns.Length; field++)
				{
					if (!sql.Equals(string.Empty))
						sql += ", ";
					sql += columns[field].Trim() + "=" + values[field].Trim();
				}
				sql = "update LogRecords set " +
					  sql +
					  " where Key=" +
					  Constants.DoubleQuote + ((DeviceRecord)_record).Key + Constants.DoubleQuote;

				base.Update(sql);
			}
			catch (Exception ex)
			{
				ErrorHandler.GetInstance().LogException("UpdateLogRecord.Update error: ", ex);
			}
		}
	}
}
