//public bool DeleteAll( Entity parent, ref SaveStatus status )
        //{
        //	bool isValid = true;
        //	//Entity parent = EntityManager.GetEntity( parentUid );
        //	if ( parent == null || parent.Id == 0 )
        //	{
        //		status.AddError( thisClassName + ".DeleteAll Error - the provided target parent entity was not provided." );
        //		return false;
        //	}
        //	using ( var context = new EntityContext() )
        //	{
        //		context.EarningsProfile.RemoveRange( context.EarningsProfile.Where( s => s.EntityId == parent.Id ) );
        //		int count = context.SaveChanges();
        //		if ( count > 0 )
        //		{
        //			isValid = true;
        //		}
        //		else
        //		{
        //			//if doing a delete on spec, may not have been any properties
        //		}
        //	}

        //	return isValid;
        //}
        /// <summary>
        /// Parts:
        /// - Jurisdiction
        /// - DataSetProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool UpdateParts(ThisEntity entity, ref SaveStatus status)
        {
            bool   isAllValid    = true;
            Entity relatedEntity = EntityManager.GetEntity(entity.RowId);

            if (relatedEntity == null || relatedEntity.Id == 0)
            {
                status.AddError("Error - the related Entity was not found.");
                return(false);
            }

            //JurisdictionProfile
            Entity_JurisdictionProfileManager jpm = new Entity_JurisdictionProfileManager();

            //do deletes - NOTE: other jurisdictions are added in: UpdateAssertedIns
            jpm.DeleteAll(relatedEntity, ref status);
            if (!jpm.SaveList(entity.Jurisdiction, entity.RowId, Entity_JurisdictionProfileManager.JURISDICTION_PURPOSE_SCOPE, ref status))
            {
                isAllValid = false;
            }
            //datasetProfiles
            if (!new DataSetProfileManager().SaveList(entity.RelevantDataSet, relatedEntity, ref status))
            {
                isAllValid = false;
            }

            return(isAllValid);
        }
        public static void MapToDB(ThisEntity input, DBEntity output)
        {
            //want output ensure fields input create are not wiped
            if (output.Id == 0)
            {
                output.CTID = input.CTID;
            }
            //if ( !string.IsNullOrWhiteSpace( input.CredentialRegistryId ) )
            //	output.CredentialRegistryId = input.CredentialRegistryId;

            output.Id = input.Id;
            //output.EntityStateId = input.EntityStateId;
            output.Name              = GetData(input.Name);
            output.Description       = GetData(input.Description);
            output.LowEarnings       = input.LowEarnings;
            output.MedianEarnings    = input.MedianEarnings;
            output.HighEarnings      = input.HighEarnings;
            output.PostReceiptMonths = input.PostReceiptMonths;

            output.Source = GetUrlData(input.Source);
            if (IsValidDate(input.DateEffective))
            {
                output.DateEffective = DateTime.Parse(input.DateEffective);
            }
            else
            {
                output.DateEffective = null;
            }
            //======================================================================
        }
        public static void MapFromDB(DBEntity input, ThisEntity output,
                                     bool includingParts)
        {
            output.Id            = input.Id;
            output.RowId         = input.RowId;
            output.EntityStateId = input.EntityStateId;
            output.Name          = input.Name == null ? "" : input.Name;
            output.Description   = input.Description == null ? "" : input.Description;
            output.CTID          = input.CTID;
            if (IsValidDate(input.DateEffective))
            {
                output.DateEffective = (( DateTime )input.DateEffective).ToString("yyyy-MM-dd");
            }
            else
            {
                output.DateEffective = "";
            }
            //
            output.LowEarnings       = input.LowEarnings ?? 0;
            output.MedianEarnings    = input.MedianEarnings ?? 0;
            output.HighEarnings      = input.HighEarnings ?? 0;
            output.PostReceiptMonths = input.PostReceiptMonths ?? 0;
            output.Source            = GetUrlData(input.Source);

            if (IsValidDate(input.Created))
            {
                output.Created = ( DateTime )input.Created;
            }
            if (IsValidDate(input.LastUpdated))
            {
                output.LastUpdated = ( DateTime )input.LastUpdated;
            }



            if (string.IsNullOrWhiteSpace(output.CTID) || output.EntityStateId < 3)
            {
                output.IsReferenceVersion = true;
                return;
            }
            //=====
            var relatedEntity = EntityManager.GetEntity(output.RowId, false);

            if (relatedEntity != null && relatedEntity.Id > 0)
            {
                output.EntityLastUpdated = relatedEntity.LastUpdated;
            }

            //components
            if (includingParts)
            {
                //
                output.Jurisdiction = Entity_JurisdictionProfileManager.Jurisdiction_GetAll(output.RowId);
                //get datasetprofiles
                output.RelevantDataSet = DataSetProfileManager.GetAll(output.RowId, true);
            }
        }         //
        //public int AddPendingRecord( Guid entityUid, string ctid, string registryAtId, ref string status )
        //{
        //	DBEntity efEntity = new DBEntity();
        //	try
        //	{
        //		using ( var context = new EntityContext() )
        //		{
        //			if ( !IsValidGuid( entityUid ) )
        //			{
        //				status = thisClassName + " - A valid GUID must be provided to create a pending entity";
        //				return 0;
        //			}
        //			//quick check to ensure not existing
        //			ThisEntity entity = GetByCtid( ctid );
        //			if ( entity != null && entity.Id > 0 )
        //				return entity.Id;

        //			//only add DB required properties
        //			//NOTE - an entity will be created via trigger
        //			efEntity.Name = "Placeholder until full document is downloaded";
        //			efEntity.Description = "Placeholder until full document is downloaded";
        //			efEntity.EntityStateId = 1;
        //			efEntity.RowId = entityUid;
        //			//watch that Ctid can be  updated if not provided now!!
        //			efEntity.CTID = ctid;
        //			efEntity.Source = registryAtId;

        //			efEntity.Created = System.DateTime.Now;
        //			efEntity.LastUpdated = System.DateTime.Now;

        //			context.EarningsProfile.Add( efEntity );
        //			int count = context.SaveChanges();
        //			if ( count > 0 )
        //				return efEntity.Id;

        //			status = thisClassName + " Error - the save was not successful, but no message provided. ";
        //		}
        //	}

        //	catch ( Exception ex )
        //	{
        //		string message = FormatExceptions( ex );
        //		LoggingHelper.LogError( ex, thisClassName + string.Format( ".AddPendingRecord. entityUid:  {0}, ctid: {1}", entityUid, ctid ) );
        //		status = thisClassName + " Error - the save was not successful. " + message;

        //	}
        //	return 0;
        //}

        public bool ValidateProfile(ThisEntity profile, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            if (string.IsNullOrWhiteSpace(profile.Description))
            {
                status.AddWarning("An EarningsProfile Description must be entered");
            }


            return(status.WasSectionValid);
        }
        public static ThisEntity GetBasic(int id)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.EarningsProfile
                                .SingleOrDefault(s => s.Id == id);

                if (item != null && item.Id > 0)
                {
                    MapFromDB(item, entity, false);
                }
            }

            return(entity);
        }
        public static ThisEntity GetByCtid(string ctid)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.EarningsProfile
                                .FirstOrDefault(s => s.CTID.ToLower() == ctid.ToLower());

                if (item != null && item.Id > 0)
                {
                    MapFromDB(item, entity, false);
                }
            }

            return(entity);
        }
        //
        public static ThisEntity GetDetails(int id)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.EarningsProfile
                                .SingleOrDefault(s => s.Id == id);

                if (item != null && item.Id > 0)
                {
                    //check for virtual deletes
                    if (item.EntityStateId == 0)
                    {
                        return(entity);
                    }

                    MapFromDB(item, entity, true);
                }
            }

            return(entity);
        }
        public bool Save(ThisEntity entity, Entity parentEntity, ref SaveStatus status)
        {
            bool isValid = true;
            int  count   = 0;

            try
            {
                using (var context = new EntityContext())
                {
                    if (ValidateProfile(entity, ref status) == false)
                    {
                        //return false;
                    }
                    //actually will always be an add
                    if (entity.Id > 0)
                    {
                        //TODO - consider if necessary, or interferes with anything
                        context.Configuration.LazyLoadingEnabled = false;
                        DBEntity efEntity = context.EarningsProfile
                                            .FirstOrDefault(s => s.Id == entity.Id);

                        if (efEntity != null && efEntity.Id > 0)
                        {
                            //fill in fields that may not be in entity
                            entity.RowId = efEntity.RowId;

                            MapToDB(entity, efEntity);

                            if (efEntity.EntityStateId == 0)
                            {
                                var url = string.Format(UtilityManager.GetAppKeyValue("credentialFinderSite") + "EarningsProfile/{0}", efEntity.Id);
                                //notify, and???
                                //EmailManager.NotifyAdmin( "Previously Deleted EarningsProfile has been reactivated", string.Format( "<a href='{2}'>EarningsProfile: {0} ({1})</a> was deleted and has now been reactivated.", efEntity.Name, efEntity.Id, url ) );
                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "EarningsProfile",
                                    Activity         = "Import",
                                    Event            = "Reactivate",
                                    Comment          = string.Format("EarningsProfile had been marked as deleted, and was reactivted by the import. CTID: {0}, SWP: {1}", entity.CTID, entity.Source),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);
                            }
                            //assume and validate, that if we get here we have a full record
                            if (efEntity.EntityStateId != 2)
                            {
                                efEntity.EntityStateId = 3;
                            }

                            //if ( IsValidDate( status.EnvelopeCreatedDate ) && status.LocalCreatedDate < efEntity.Created )
                            //{
                            //	efEntity.Created = status.LocalCreatedDate;
                            //}
                            if (IsValidDate(status.EnvelopeUpdatedDate) && status.LocalUpdatedDate != efEntity.LastUpdated)
                            {
                                efEntity.LastUpdated = status.LocalUpdatedDate;
                            }
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                if (IsValidDate(status.EnvelopeUpdatedDate))
                                {
                                    efEntity.LastUpdated = status.LocalUpdatedDate;
                                }
                                else
                                {
                                    efEntity.LastUpdated = DateTime.Now;
                                }
                                //NOTE efEntity.EntityStateId is set to 0 in delete method )
                                count = context.SaveChanges();
                                //can be zero if no data changed
                                if (count >= 0)
                                {
                                    isValid = true;
                                }
                                else
                                {
                                    //?no info on error

                                    isValid = false;
                                    string message = string.Format(thisClassName + ".Save Failed", "Attempted to update a EarningsProfile. The process appeared to not work, but was not an exception, so we have no message, or no clue. EarningsProfile: {0}, Id: {1}", entity.Name, entity.Id);
                                    status.AddError("Error - the update was not successful. " + message);
                                    EmailManager.NotifyAdmin(thisClassName + ".Save Failed Failed", message);
                                }
                            }
                            else
                            {
                                //update entity.LastUpdated - assuming there has to have been some change in related data
                                //new EntityManager().UpdateModifiedDate( entity.RowId, ref status );
                            }
                            if (isValid)
                            {
                                if (!UpdateParts(entity, ref status))
                                {
                                    isValid = false;
                                }

                                SiteActivity sa = new SiteActivity()
                                {
                                    ActivityType     = "EarningsProfile",
                                    Activity         = "Import",
                                    Event            = "Update",
                                    Comment          = string.Format("EarningsProfile was updated by the import. CTID: {0}, Source: {1}", entity.CTID, entity.Source),
                                    ActivityObjectId = entity.Id
                                };
                                new ActivityManager().SiteActivityAdd(sa);

                                //if ( isValid || partsUpdateIsValid )
                                new EntityManager().UpdateModifiedDate(entity.RowId, ref status, efEntity.LastUpdated);
                            }
                        }
                        else
                        {
                            status.AddError("Error - update failed, as record was not found.");
                        }
                    }
                    else
                    {
                        //add
                        int newId = Add(entity, parentEntity, ref status);
                        if (newId == 0 || status.HasErrors)
                        {
                            isValid = false;
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                string message = HandleDBValidationError(dbex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name), "EarningsProfile");
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Save. id: {0}, Name: {1}", entity.Id, entity.Name));
                status.AddError(thisClassName + ".Save(). Error - the save was not successful. " + message);
                isValid = false;
            }


            return(isValid);
        }
        /// <summary>
        /// add a EarningsProfile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private int Add(ThisEntity entity, Entity parentEntity, ref SaveStatus status)
        {
            DBEntity efEntity = new DBEntity();

            using (var context = new EntityContext())
            {
                try
                {
                    MapToDB(entity, efEntity);

                    if (IsValidGuid(entity.RowId))
                    {
                        efEntity.RowId = entity.RowId;
                    }
                    else
                    {
                        efEntity.RowId = Guid.NewGuid();
                    }
                    efEntity.EntityStateId = 3;
                    //the envelope date may not reflect when the earning profile was added
                    //if ( IsValidDate( status.EnvelopeCreatedDate ) )
                    //{
                    //	efEntity.Created = status.LocalCreatedDate;
                    //	efEntity.LastUpdated = status.LocalCreatedDate;
                    //}
                    //else
                    {
                        efEntity.Created     = System.DateTime.Now;
                        efEntity.LastUpdated = System.DateTime.Now;
                    }

                    context.EarningsProfile.Add(efEntity);

                    // submit the change to database
                    int count = context.SaveChanges();
                    if (count > 0)
                    {
                        if (efEntity.Id == 0)
                        {
                            List <string> messages = new List <string>();
                            Delete(efEntity.Id, ref messages);

                            efEntity.RowId = Guid.NewGuid();
                            context.EarningsProfile.Add(efEntity);
                            count        = context.SaveChanges();
                            entity.Id    = efEntity.Id;
                            entity.RowId = efEntity.RowId;
                        }
                        else
                        {
                            entity.Id    = efEntity.Id;
                            entity.RowId = efEntity.RowId;
                        }
                        //add log entry
                        SiteActivity sa = new SiteActivity()
                        {
                            ActivityType     = "EarningsProfile",
                            Activity         = "Import",
                            Event            = "Add",
                            Comment          = string.Format("Full EarningsProfile was added by the import. CTID: {0}, Desc: {1}", entity.CTID, entity.Description),
                            ActivityObjectId = entity.Id
                        };
                        new ActivityManager().SiteActivityAdd(sa);
                        //TODO
                        new Entity_EarningsProfileManager().Add(parentEntity.EntityUid, entity.Id, ref status);

                        if (UpdateParts(entity, ref status) == false)
                        {
                        }

                        return(efEntity.Id);
                    }
                    else
                    {
                        //?no info on error

                        string message = thisClassName + string.Format(". Add Failed", "Attempted to add a EarningsProfile. The process appeared to not work, but was not an exception, so we have no message, or no clue. EarningsProfile: {0}, ctid: {1}", entity.Name, entity.CTID);
                        status.AddError(thisClassName + ". Error - the add was not successful. " + message);
                        EmailManager.NotifyAdmin("EarningsProfileManager. Add Failed", message);
                    }
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    string message = HandleDBValidationError(dbex, thisClassName + ".Add() ", "EarningsProfile");
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. " + message);

                    LoggingHelper.LogError(message, true);
                }
                catch (Exception ex)
                {
                    string message = FormatExceptions(ex);
                    LoggingHelper.LogError(ex, thisClassName + string.Format(".Add(), CTID: {0}\r\n", efEntity.CTID));
                    status.AddError(thisClassName + ".Add(). Error - the save was not successful. \r\n" + message);
                }
            }

            return(efEntity.Id);
        }