﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Light.DataCore
{
	class PrimitiveDataDefine : DataDefine
	{
		public PrimitiveDataDefine (Type type, bool isNullable)
			: base (type, isNullable)
		{
			_typeCode = Type.GetTypeCode (type);
		}

		TypeCode _typeCode;

		/// <summary>
		/// Loads the data.
		/// </summary>
		/// <returns>The data.</returns>
		/// <param name="context">Context.</param>
		/// <param name="datareader">Datareader.</param>
		/// <param name="state">State.</param>
		public override object LoadData (DataContext context, IDataReader datareader, object state)
		{
			object obj = datareader [0];
			return GetValue (obj);
		}

		object GetValue (object obj)
		{
			if (Object.Equals (obj, DBNull.Value)) {
				if (!IsNullable) {
					return Utility.GetDefaultValue (_typeCode);
				}
				else {
					return null;
				}
			}
			else {
				return Convert.ChangeType (obj, ObjectType);
			}
		}
	}
}
