using System;

using BeWo.Data.Entities;

using BS.Shared.Extensions;

using NHibernate;
using NHibernate.Type;

namespace BeWo.Data
{
    /// <summary>
    /// UpdInsInterceptor
    /// Mit freundlicher Genehmigung von Prof. Dr. Uwe Südbeck. In Anlehnung an ContextObjectSaveInterceptor.java (Gerig)
    /// Uwe.Suedbeck@beyondsoft.de
    /// </summary>
    public class UpdInsInterceptor : EmptyInterceptor
    {
        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
        {
			int i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_UdpUser);
	        if (i >= 0)
	        {
		        if (LoggedInUserOperationContextExt.Current != null)
		        {

			        currentState[i] =
				        LoggedInUserOperationContextExt.Current.User.Employee.Person.FirstName + " " +
				        LoggedInUserOperationContextExt.Current.User.Employee.Person.LastName;
		        }
		        else
		        {
			        currentState[i] = null;
		        }
	        }
	        return base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types);
        }

        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            if (LoggedInUserOperationContextExt.Current != null)
            {
	            int i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_InsUser);
				if (i >= 0)
					state[i] = LoggedInUserOperationContextExt.Current.User.Employee.Person.FirstName + " " + LoggedInUserOperationContextExt.Current.User.Employee.Person.LastName;
				i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_UdpUser);
				if (i >= 0)
					state[i] = LoggedInUserOperationContextExt.Current.User.Employee.Person.FirstName + " " + LoggedInUserOperationContextExt.Current.User.Employee.Person.LastName;
            }
			int i2 = propertyNames.IndexOf(BeWoEntityBase.PropertyName_InsTs);
			if (i2 >= 0)
				state[i2] = DateTime.Now;

            return base.OnSave(entity, id, state, propertyNames, types);
        }
    }
}