using System;

using BeWo.Data.Entities;

using BS.Shared.Extensions;

using NHibernate;
using NHibernate.Type;

namespace BeWoPlanerAndroid.Service
{
    public class MobileUpdInstInterceptor : EmptyInterceptor
    {
        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
        {
            var i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_UdpUser);

            if (i >= 0)
            {
                if (MobileSessionFacade.IsUserLoggedIn())
                {
                    currentState[i] = string.Format("{0}", MobileSessionFacade.EmployeeFullname);
                }
                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 (MobileSessionFacade.IsUserLoggedIn())
            {
                var i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_InsUser);
                if (i >= 0)
                {
                    state[i] = string.Format("{0}", MobileSessionFacade.EmployeeFullname);
                }

                i = propertyNames.IndexOf(BeWoEntityBase.PropertyName_UdpUser);
                if (i >= 0)
                {
                    state[i] = string.Format("{0}", MobileSessionFacade.EmployeeFullname);
                }
            }

            var i2 = propertyNames.IndexOf(BeWoEntityBase.PropertyName_InsTs);

            if (i2 >= 0)
            {
                state[i2] = DateTime.Now;
            }

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