/// <summary>
        /// get all related JurisdictionProfiles for the parent
        /// </summary>
        /// <param name="parentUId"></param>
        /// <returns></returns>
        public static List <ThisEntity> Jurisdiction_GetAll(Guid parentUid, int jprofilePurposeId = 1)
        {
            //efEntity.JProfilePurposeId
            ThisEntity        entity = new ThisEntity();
            List <ThisEntity> list   = new List <ThisEntity>();
            int count = 0;

            MC.Entity parent = EntityManager.GetEntity(parentUid);
            if (parent == null || parent.Id == 0)
            {
                return(list);
            }

            using (var context = new EntityContext())
            {
                List <DBEntity> Items = context.Entity_JurisdictionProfile
                                        .Where(s => s.EntityId == parent.Id &&
                                               s.JProfilePurposeId == jprofilePurposeId)
                                        .OrderBy(s => s.Id).ToList();

                if (Items.Count > 0)
                {
                    foreach (DBEntity item in Items)
                    {
                        entity = new ThisEntity();
                        count++;
                        //map and get regions
                        MapFromDB(item, entity, count);
                        list.Add(entity);
                    }
                }
            }

            return(list);
        }
        /// <summary>
        /// May want to use an isLast check to better handle an empty object
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool IsEmpty(ThisEntity entity, bool isLastItem = false)
        {
            bool isEmpty = false;

            //this will be problematic as the two bools default to false
            //radio buttons?
            if (string.IsNullOrWhiteSpace(entity.Description) &&
                (entity.MainJurisdiction == null || entity.MainJurisdiction.GeoNamesId == 0) &&
                (entity.JurisdictionException == null || entity.JurisdictionException.Count == 0)
                )
            {
                return(true);
            }

            return(isEmpty);
        }
        /// <summary>
        /// Get a single Jurisdiction Profile by Guid
        /// </summary>
        /// <param name="rowId"></param>
        /// <returns></returns>
        public static ThisEntity Get(Guid rowId)
        {
            ThisEntity entity = new ThisEntity();

            using (var context = new EntityContext())
            {
                DBEntity item = context.Entity_JurisdictionProfile
                                .SingleOrDefault(s => s.RowId == rowId);

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

            return(entity);
        }
        public bool UpdateParts(ThisEntity entity, bool isAdd, ref SaveStatus status)
        {
            bool isValid = true;

            EntityPropertyManager mgr = new EntityPropertyManager();

            if (mgr.AddProperties(entity.JurisdictionAssertion, entity.RowId, CodesManager.ENTITY_TYPE_JURISDICTION_PROFILE, CodesManager.PROPERTY_CATEGORY_JurisdictionAssertionType, false, ref status) == false)
            {
                isValid = false;
            }

            int id = GeoCoordinates_Add(entity.MainJurisdiction, entity.Id, ref status);

            if (entity.JurisdictionException != null)
            {
                foreach (var gc in entity.JurisdictionException)
                {
                    GeoCoordinates_Add(gc, entity.Id, ref status);
                }
            }
            return(isValid);
        }
        /// <summary>
        /// Add a jurisdiction profile
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="property">Can be blank. Set to a property where additional validation is necessary</param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool Add(ThisEntity entity, string property, ref SaveStatus status, int assertedInTypeId = 0)
        {
            bool isValid = true;

            using (var context = new EntityContext())
            {
                if (entity == null || !IsValidGuid(entity.ParentEntityUid))
                {
                    status.AddWarning("Error - missing an identifier for the JurisdictionProfile");
                    return(false);
                }

                //ensure we have a parentId/EntityId
                Entity parent = EntityManager.GetEntity(entity.ParentEntityUid);
                if (parent == null || parent.Id == 0)
                {
                    status.AddWarning("Error - the parent entity was not found.");
                    return(false);
                }

                //check for Empty
                //==> not sure what is the minimum required fields!
                bool isEmpty = false;

                if (ValidateProfile(entity, property, ref isEmpty, ref status) == false)
                {
                    return(false);
                }
                if (isEmpty)
                {
                    //status.AddWarning( "Error - Jurisdiction profile is empty. " );
                    return(false);
                }


                //id = JurisdictionProfile_Add( entity, ref status );
                DBEntity efEntity = new DBEntity();
                MapToDB(entity, efEntity);
                efEntity.EntityId = parent.Id;
                if (IsValidGuid(entity.RowId))
                {
                    efEntity.RowId = entity.RowId;
                }
                else
                {
                    efEntity.RowId = Guid.NewGuid();
                }

                entity.RowId = efEntity.RowId;

                if (efEntity.JProfilePurposeId == null || efEntity.JProfilePurposeId == 0)
                {
                    efEntity.JProfilePurposeId = 1;
                }

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

                context.Entity_JurisdictionProfile.Add(efEntity);

                int count = context.SaveChanges();
                if (count > 0)
                {
                    entity.Id = efEntity.Id;
                    //update parts
                    UpdateParts(entity, true, ref status);
                    //??????? why
                    //UpdateJPRegions( entity,  ref status );
                }
            }

            return(isValid);
        }
        private static void MapFromDB(DBEntity from, ThisEntity to, int count)
        {
            to.Id       = from.Id;
            to.RowId    = from.RowId;
            to.ParentId = (int)from.EntityId;

            //these will probably no lonber be necessary
            to.ParentTypeId    = from.Entity.EntityTypeId;
            to.ParentEntityUid = from.Entity.EntityUid;

            to.JProfilePurposeId = from.JProfilePurposeId != null ? ( int )from.JProfilePurposeId : 1;

            if (IsGuidValid(from.AssertedByAgentUid))
            {
                to.AssertedBy = ( Guid )from.AssertedByAgentUid;

                to.AssertedByOrganization = OrganizationManager.GetBasics(to.AssertedBy);
            }

            if ((from.Description ?? "") == "Auto-saved Jurisdiction")
            {
                to.Description = "";
            }
            else
            {
                to.Description = from.Description;
            }

            if (from.Created != null)
            {
                to.Created = ( DateTime )from.Created;
            }

            if (from.LastUpdated != null)
            {
                to.LastUpdated = ( DateTime )from.LastUpdated;
            }



            List <MC.GeoCoordinates> regions = GetAll(to.Id, false);

            if (regions != null && regions.Count > 0)
            {
                to.MainJurisdiction = regions[0];
            }
            to.JurisdictionException = GetAll(to.Id, true);


            if (to.MainJurisdiction != null && to.MainJurisdiction.GeoNamesId > 0 && to.MainJurisdiction.Name != "Earth")
            {
                to.IsGlobalJurisdiction = false;
            }
            else
            {
                to.IsGlobalJurisdiction = from.IsGlobalJurisdiction;
            }

            if (!string.IsNullOrWhiteSpace(from.Description))
            {
                to.ProfileSummary = from.Description;
            }
            else
            {
                if (to.MainJurisdiction != null && to.MainJurisdiction.GeoNamesId > 0)
                {
                    to.ProfileSummary = to.MainJurisdiction.ProfileSummary;
                }
                else
                {
                    if ((bool)(to.IsGlobalJurisdiction ?? false))
                    {
                        to.ProfileSummary = "Global";
                    }
                    else
                    {
                        to.ProfileSummary = "JurisdictionProfile Summary - " + count.ToString();
                    }
                }
            }
            if ((from.AssertedInTypeId ?? 0) > 0 && from.Codes_AssertionType != null)
            {
                to.AssertedInTypeId = (int)from.AssertedInTypeId;
                to.AssertedInType   = from.Codes_AssertionType.Title;
                Enumeration ja = new Enumeration()
                {
                    Name = "Jurisdiction Assertions"
                };
                EnumeratedItem ei = new EnumeratedItem()
                {
                    Id = to.AssertedInTypeId, Name = to.AssertedInType
                };
                to.JurisdictionAssertion.Items.Add(ei);
            }
            //***TODO ** handle differently?
            //use of properties, requires creating an Entity for Jurisdiction???
            if (to.JProfilePurposeId == 3)
            {
            }
            //to.JurisdictionAssertion = EntityPropertyManager.FillEnumeration( to.RowId, CodesManager.PROPERTY_CATEGORY_JurisdictionAssertionType );
        }         //
        /// <summary>
        /// Mapping from interface model to entity model
        /// Assuming that for updates, the entity model is always populated from DB, so here we can make assumptions regarding what can be updated.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        private static void MapToDB(ThisEntity from, DBEntity to)
        {
            to.Id = from.Id;
            //to.EntityId = from.ParentId;
            //don't allow a change if an update
            if (from.Id == 0)
            {
                to.JProfilePurposeId = from.JProfilePurposeId > 0 ? from.JProfilePurposeId : 1;
            }
            else
            {
                //handle unexpected
                if (to.JProfilePurposeId == null)
                {
                    to.JProfilePurposeId = 1;
                }
            }

            //from.MainJurisdiction is likely null
            if (from.MainJurisdiction != null && from.MainJurisdiction.GeoNamesId == 0)
            {
                //List<MC.GeoCoordinates> regions = GetAll( to.Id, false );
                //if ( regions != null && regions.Count > 0 )
                //{
                //	from.MainJurisdiction = regions[ 0 ];
                //}
            }

            if (from.MainJurisdiction != null && !string.IsNullOrWhiteSpace(from.MainJurisdiction.Name))
            {
                to.Name = from.MainJurisdiction.Name;
            }
            else
            {
                to.Name = "Default jurisdiction";
            }
            to.Description = from.Description;


            //TODO - if a main jurisdiction exists, then global should be false
            //may not be available
            if (from.MainJurisdiction != null &&
                (from.MainJurisdiction.GeoURI ?? "").Length > 0 &&
                from.MainJurisdiction.Name != "Earth")
            {
                to.IsGlobalJurisdiction = false;
            }

            else if (from.IsGlobalJurisdiction != null)
            {
                to.IsGlobalJurisdiction = from.IsGlobalJurisdiction;
            }
            else
            {
                to.IsGlobalJurisdiction = null;
            }
            if (!IsGuidValid(from.AssertedBy) && from.AssertedByList != null && from.AssertedByList.Count > 0)
            {
                from.AssertedBy = from.AssertedByList[0];
            }

            if (IsGuidValid(from.AssertedBy))
            {
                if (to.Id > 0 && to.AssertedByAgentUid != from.AssertedBy)
                {
                    if (IsGuidValid(to.AssertedByAgentUid))
                    {
                        //need to remove the previous roles on change of asserted by
                        //string statusMessage = "";
                        //new Entity_AgentRelationshipManager().Delete( to.RowId, to.AssertedByAgentUid, Entity_AgentRelationshipManager.ROLE_TYPE_OWNER, ref statusMessage );
                    }
                }
                to.AssertedByAgentUid = from.AssertedBy;
            }
            else
            {
                to.AssertedByAgentUid = null;
            }

            if (from.AssertedInTypeId > 0)
            {
                to.AssertedInTypeId = ( int )from.AssertedInTypeId;
            }
            else
            {
                to.AssertedInTypeId = null;
            }
        }
        public bool ValidateProfile(ThisEntity profile, string property, ref bool isEmpty, ref SaveStatus status)
        {
            status.HasSectionErrors = false;
            isEmpty = false;
            //this will be problematic as the two bools default to false
            if (string.IsNullOrWhiteSpace(profile.Description) &&
                (profile.MainJurisdiction == null || profile.MainJurisdiction.GeoNamesId == 0) &&
                (profile.JurisdictionException == null || profile.JurisdictionException.Count == 0) &&
                (!IsValidGuid(profile.AssertedBy)) &&
                (profile.JurisdictionAssertion == null || profile.JurisdictionAssertion.Items.Count == 0)
                )
            {
                //isEmpty = true;
                //status.AddWarning( "No data has been entered, save was cancelled." );
                //return false;
            }
            if (property == "JurisdictionAssertions" && profile.Id > 0)
            {
                if (!IsValidGuid(profile.AssertedBy))
                {
                    status.AddWarning("Please select the Agent that makes these assertions.");
                }
                if (profile.JurisdictionAssertion == null || profile.JurisdictionAssertion.Items.Count == 0)
                {
                    status.AddWarning("Please select at least one assertion.");
                }
            }

            if (profile.MainJurisdiction == null || profile.MainJurisdiction.GeoNamesId == 0)
            {
                //doesn't make sense here
                //List<MC.GeoCoordinates> regions = GetAll( profile.Id, false );
                //if ( regions != null && regions.Count > 0 )
                //{
                //	profile.MainJurisdiction = regions[ 0 ];
                //}
            }
            //need to have a main jurisdiction, or is global
            if (profile.MainJurisdiction != null &&
                (profile.MainJurisdiction.GeoURI ?? "").Length > 0 &&
                profile.MainJurisdiction.Name != "Earth")
            {
                //should not have global
                if ((profile.IsGlobalJurisdiction ?? false) == true)
                {
                    status.AddWarning("Is Global cannot be set to 'Is Global' when an main region has been selected.");
                }
            }
            else
            {
                //no regions, must specify global
                //may want to make configurable
                //if ( ( profile.IsGlobalJurisdiction ?? false ) == false )
                //{
                //	if ( profile.Description != "Auto-saved Jurisdiction" )
                //	{
                //		if ( UtilityManager.GetAppKeyValue( "requireRegionOrIsGlobal", false ) == true )
                //		{
                //			status.AddWarning( "Please select a main region, OR set 'Is Global' to 'This jurisdiction is global'." );
                //		}
                //	}
                //}
            }

            return(!status.HasSectionErrors);
        }