using System;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using Medivators.Common;

namespace Medivators.BusinessObjects
{
	public class LogRecordDataMapper : IDataMapper
	{
		private List<IBusinessObject> _list = new DeviceRecordList();

		public List<IBusinessObject> BusinessObjectCollection
		{
			get {return _list;}
		}
		public System.Data.OleDb.OleDbDataReader Reader
		{
			set
			{
				string fieldName = string.Empty; 
				try
				{
					while (value.Read())
					{
						IDeviceRecord rec = null;

						//  get record type to determine what 
						//	type of log record to instantiate
						DeviceRecordTypes recType = (DeviceRecordTypes)Enum.Parse(typeof(DeviceRecordTypes), (string)value["RecordType"]);
						switch (recType)
						{
							case DeviceRecordTypes.CycleEnd:
							case DeviceRecordTypes.CycleStart:
							case DeviceRecordTypes.LogRecord:
								rec = new DSD201EventRecord();
								break;
							default:
								rec = new TimestampedHeaderRecord();
								break;
						}

						#region for loop & switch statement reads fields into records

						for (int fldNo = 0; fldNo < value.FieldCount; fldNo++)
						{
							if (!value.IsDBNull(fldNo))
							{
								fieldName = value.GetName(fldNo).ToLower();
								switch (fieldName)
								{
									//	keys are not listed as classes calculates their own keys
									case "machineid":
										((DeviceRecord)rec).MachineID = value.GetInt32(fldNo);
										break;
									case "station":
										((DeviceRecord)rec).Station = value.GetString(fldNo);
										break;
									case "recordtype":
										((DeviceRecord)rec).RecordType = recType;
										break;
									case "isalarm":
										((DeviceRecord)rec).IsAlarm = value.GetBoolean(fldNo);
										break;
									case "lognumber":
										((DeviceRecord)rec).LogNumber = value.GetInt32(fldNo);
										break;
									case "text":
										((DeviceRecord)rec).Text = value.GetString(fldNo);
										break;
									case "program":
										((DSD201EventRecord)rec).Program = value.GetInt16(fldNo);
										break;
									case "data":
										((TimestampedHeaderRecord)rec).Data = value.GetString(fldNo);
										break;
									case "timestamp":
										((ITimestampedDeviceRecord)rec).Timestamp = value.GetDateTime(fldNo);
										break;
								}
							}
						}
						#endregion

						_list.Add((DeviceRecord)rec);
					}
				}
				catch (Exception ex)
				{
					string message = "LogRecordDataMapper.Reader error. ";
					if ( ! fieldName.Equals(string.Empty) )
						message += " Casting field [" + fieldName + "] ";
					message += " Ex: "; 
					ErrorHandler.GetInstance().LogException(message, ex);
				}
			}
		}
		public void Dispose()
		{
			if ( _list != null )
				_list.Clear();
		}

		public object Data
		{
			get { return (object)_list; }
		}
	}
}
