//currently
        public bool DoesEntityExist(string ctid, ref ThisEntity entity, ref SaveStatus status)
        {
            bool exists = false;

            entity = EntityServices.HandlingExistingEntity(ctid, ref status);
            if (entity != null && entity.Id > 0)
            {
                //we know for this type, there will entity.learningopp, entity.assessment and entity.credential relationships, and quick likely blank nodes.
                return(true);
            }

            return(exists);
        }
        }         //

        public bool Import(string payload, string envelopeIdentifier, SaveStatus status)
        {
            List <string>  messages          = new List <string>();
            bool           importSuccessfull = false;
            EntityServices mgr = new EntityServices();
            //
            InputEntity input      = new InputEntity();
            var         bnodes     = new List <BNode>();
            var         mainEntity = new Dictionary <string, object>();
            //
            Dictionary <string, object> dictionary = RegistryServices.JsonToDictionary(payload);
            object graph = dictionary["@graph"];
            //serialize the graph object
            var glist = JsonConvert.SerializeObject(graph);

            //parse graph in to list of objects
            JArray graphList = JArray.Parse(glist);
            int    cntr      = 0;

            foreach (var item in graphList)
            {
                cntr++;
                if (cntr == 1)
                {
                    var main = item.ToString();
                    //may not use this. Could add a trace method
                    mainEntity = RegistryServices.JsonToDictionary(main);
                    input      = JsonConvert.DeserializeObject <InputEntity>(main);
                }
                else
                {
                    var bn = item.ToString();
                    //20-07-02 need to handle the enhanced bnodes
                    bnodes.Add(JsonConvert.DeserializeObject <BNode>(bn));
                }
            }

            ///============= process =============================
            MappingHelperV3 helper = new MappingHelperV3(3);

            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();

            string ctid = input.CTID;

            status.Ctid = ctid;
            string referencedAtId = input.CtdlId;

            LoggingHelper.DoTrace(5, "		ctid: "+ ctid);
            LoggingHelper.DoTrace(5, "		@Id: "+ input.CtdlId);
            LoggingHelper.DoTrace(5, "		name: "+ input.Name.ToString());

            if (status.DoingDownloadOnly)
            {
                return(true);
            }

            //add/updating TransferValue
            if (!DoesEntityExist(input.CTID, ref output, ref status))
            {
                //set the rowid now, so that can be referenced as needed
                output.RowId = Guid.NewGuid();
            }
            helper.currentBaseObject = output;

            output.Name        = helper.HandleLanguageMap(input.Name, output, "Name");
            output.Description = helper.HandleLanguageMap(input.Description, output, "Description");
            output.CTID        = input.CTID;
            //TBD handling of referencing third party publisher
            if (!string.IsNullOrWhiteSpace(status.DocumentPublishedBy))
            {
                //output.PublishedByOrganizationCTID = status.DocumentPublishedBy;
                var porg = OrganizationManager.GetSummaryByCtid(status.DocumentPublishedBy);
                if (porg != null && porg.Id > 0)
                {
                    //TODO - store this in a json blob??????????
                    //this will result in being added to Entity.AgentRelationship
                    output.PublishedBy = new List <Guid>()
                    {
                        porg.RowId
                    };
                }
                else
                {
                    //if publisher not imported yet, all publishee stuff will be orphaned
                    var entityUid = Guid.NewGuid();
                    var statusMsg = "";
                    var resPos    = referencedAtId.IndexOf("/resources/");
                    var swp       = referencedAtId.Substring(0, (resPos + "/resources/".Length)) + status.DocumentPublishedBy;
                    int orgId     = new OrganizationManager().AddPendingRecord(entityUid, status.DocumentPublishedBy, swp, ref statusMsg);
                }
            }
            else
            {
                //may need a check for existing published by to ensure not lost
                if (output.Id > 0)
                {
                    if (output.OrganizationRole != null && output.OrganizationRole.Any())
                    {
                        var publishedByList = output.OrganizationRole.Where(s => s.RoleTypeId == 30).ToList();
                        if (publishedByList != null && publishedByList.Any())
                        {
                            var pby = publishedByList[0].ActingAgentUid;
                            output.PublishedBy = new List <Guid>()
                            {
                                publishedByList[0].ActingAgentUid
                            };
                        }
                    }
                }
            }
            output.CredentialRegistryId = envelopeIdentifier;
            output.SubjectWebpage       = input.SubjectWebpage;
            //****owner missing
            output.OwnedBy = helper.MapOrganizationReferenceGuids("TransferValue.OwnedBy", input.OwnedBy, ref status);
            if (output.OwnedBy != null && output.OwnedBy.Count > 0)
            {
                output.OwningAgentUid        = output.OwnedBy[0];
                helper.CurrentOwningAgentUid = output.OwnedBy[0];
            }

            //
            //output.DerivedFromForImport = helper.MapEntityReferenceGuids( "TransferValue.DerivedFrom", input.DerivedFrom, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE, ref status );
            output.DerivedFromForImport = helper.MapEntityReferences("TransferValue.DerivedFrom", input.DerivedFrom, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE, ref status);
            //
            output.DevelopmentProcess = helper.FormatProcessProfile(input.DevelopmentProcess, ref status);


            //TBD - will replace codedNotation
            //output.CodedNotation = input.CodedNotation;
            //TBD - store more stuff as Json
            output.Identifier = helper.MapIdentifierValueList(input.Identifier);
            if (output.Identifier != null && output.Identifier.Count() > 0)
            {
                output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
            }
            //

            //need to handle partial dates
            output.StartDate = input.StartDate;
            output.EndDate   = input.EndDate;
            //
            output.LifecycleStatusType = helper.MapCAOToString(input.LifecycleStatusType);
            //output.LifecycleStatusType = helper.MapCAOToEnumermation( input.LifecycleStatusType );
            //adding common import pattern
            //new PathwayManager().Save( ef, ref status, true );

            //

            output.TransferValue = helper.HandleValueProfileList(input.TransferValue, "TransferValueProfile.TransferValue");
            if (output.TransferValue != null && output.TransferValue.Count() > 0)
            {
                output.TransferValueJson = JsonConvert.SerializeObject(output.TransferValue, MappingHelperV3.GetJsonSettings());
            }
            //the class type must be provided for a blank node
            //TODO - make sure code handles extended properties
            //20-07-29 - getting duplicates - need to properly check for existing
            //			- actually a common approach is to delete all existing. this suggests NOT creating the pending entities!!
            //			- could be part of exists check
            output.TransferValueForImport = helper.MapEntityReferenceGuids("TransferValue.TransferValueFor", input.TransferValueFor, 0, ref status);
            if (output.TransferValueForImport != null && output.TransferValueForImport.Count() > 0)
            {
                //TransferValueForImport is a list of guids which could reference a blank node
                foreach (var item in output.TransferValueForImport)
                {
                    var tlo = ProfileServices.GetEntityAsTopLevelObject(item);
                    if (tlo != null && tlo.Id > 0)
                    {
                        output.TransferValueFor.Add(tlo);
                    }
                    else
                    {
                        //log error
                    }
                }
                //get all object as
                output.TransferValueForJson = JsonConvert.SerializeObject(output.TransferValueFor, MappingHelperV3.GetJsonSettings());
            }
            output.TransferValueFromImport = helper.MapEntityReferenceGuids("TransferValue.TransferValueFrom", input.TransferValueFrom, 0, ref status);
            if (output.TransferValueFromImport != null && output.TransferValueFromImport.Count() > 0)
            {
                //TransferValueFromImport is a list of guids which could reference a blank node
                foreach (var item in output.TransferValueFromImport)
                {
                    var tlo = ProfileServices.GetEntityAsTopLevelObject(item);
                    if (tlo != null && tlo.Id > 0)
                    {
                        output.TransferValueFrom.Add(tlo);
                    }
                    else
                    {
                        //log error
                    }
                }
                //get all object as
                output.TransferValueFromJson = JsonConvert.SerializeObject(output.TransferValueFrom, MappingHelperV3.GetJsonSettings());
            }

            importSuccessfull = new TransferValueServices().Import(output, ref status);
            //
            status.DocumentId    = output.Id;
            status.DetailPageUrl = string.Format("~/transfervalue/{0}", output.Id);
            status.DocumentRowId = output.RowId;

            //just in case
            if (status.HasErrors)
            {
                importSuccessfull = false;
            }

            //if record was added to db, add to/or set EntityResolution as resolved
            int ierId = new ImportManager().Import_EntityResolutionAdd(referencedAtId,
                                                                       ctid, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE,
                                                                       output.RowId,
                                                                       output.Id,
                                                                       false,
                                                                       ref messages,
                                                                       output.Id > 0);

            //

            return(importSuccessfull);
        }