private fhir.Basic WrapInBasic(fhir.SubscriptionTopic topic)
 {
     return(new fhir.Basic()
     {
         Id = topic.Id,
         Code = new fhir.CodeableConcept()
         {
             Coding = new fhir.Coding[]
             {
                 new fhir.Coding()
                 {
                     Code = "R5SubscriptionTopic",
                     System = "http://hl7.org/fhir/resource-types",
                     Display = "Backported R5 SubscriptionTopic"
                 }
             }
         },
         Extension = new fhir.Extension[]
         {
             new fhir.Extension()
             {
                 Url = "http://hl7.org/fhir/StructureDefinition/json-embedded-resource",
                 ValueString = JsonConvert.SerializeObject(
                     topic,
                     new JsonSerializerSettings()
                 {
                     NullValueHandling = NullValueHandling.Ignore,
                     ContractResolver = _contractResolver,
                 })
             }
         }
     });
 }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>Creates the topics.</summary>
        ///
        /// <remarks>Gino Canessa, 6/4/2019.</remarks>
        ///-------------------------------------------------------------------------------------------------

        private void CreateTopics()
        {
            // **** make sure our lists are clear ****

            _titleTopicDict.Clear();
            _canonicalUrlTopicDict.Clear();
            _idTopicDict.Clear();

            // **** create our known topics ****

            fhir.SubscriptionTopic topic = new fhir.SubscriptionTopic()
            {
                Title           = "admission",
                Id              = "1",
                Url             = "http://argonautproject.org/subscription-ig/Topic/admission",
                Version         = "0.4",
                Status          = "draft",
                Experimental    = true,
                Description     = "Admission Topic for testing framework and behavior",
                Date            = "2019-08-01",
                ResourceTrigger = new fhir.SubscriptionTopicResourceTrigger()
                {
                    Description   = "Beginning of a clinical encounter",
                    ResourceType  = new string[] { "Encounter" },
                    QueryCriteria = new SubscriptionTopicResourceTriggerQueryCriteria()
                    {
                        Previous    = "status:not=in-progress",
                        Current     = "status:in-progress",
                        RequireBoth = true,
                    },
                    FhirPathCriteria = "%previous.status!='in-progress' and %current.status='in-progress'",
                },
                CanFilterBy = new SubscriptionTopicCanFilterBy[]
                {
                    new SubscriptionTopicCanFilterBy()
                    {
                        SearchParamName = "patient",
                        Documentation   = "Exact match to a patient resource (reference)",
                        MatchType       = new string[] { "=", "in", "not-in" }
                    },
                },
            };

            // **** add this topic ****

            _AddOrUpdate(topic);
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>Adds or updates a Topic</summary>
        ///
        /// <remarks>Gino Canessa, 6/6/2019.</remarks>
        ///
        /// <param name="topic">The topic.</param>
        ///-------------------------------------------------------------------------------------------------

        private void _AddOrUpdate(fhir.SubscriptionTopic topic)
        {
            string localUrl = Program.UrlForResourceId("Topic", topic.Title);

            // **** check for local url already existing ****

            if (_localUrlTopicDict.ContainsKey(localUrl))
            {
                fhir.SubscriptionTopic oldTopic = _localUrlTopicDict[localUrl];

                // **** remove if this topic exists in other dictionaries ****

                RemoveIfExists(_canonicalUrlTopicDict, oldTopic.Url);
                RemoveIfExists(_titleTopicDict, localUrl);
                RemoveIfExists(_idTopicDict, oldTopic.Title);

                // **** remove from this dict ****

                _localUrlTopicDict.Remove(topic.Title);
            }

            // **** check for this canonical url already existing ****

            if (_canonicalUrlTopicDict.ContainsKey(topic.Url))
            {
                fhir.SubscriptionTopic oldTopic = _canonicalUrlTopicDict[topic.Url];

                // **** remove if this topic exists in other dictionaries ****

                RemoveIfExists(_localUrlTopicDict, localUrl);
                RemoveIfExists(_titleTopicDict, oldTopic.Url);
                RemoveIfExists(_idTopicDict, oldTopic.Title);

                // **** remove from this dict ****

                _canonicalUrlTopicDict.Remove(topic.Url);
            }

            // **** check for title already existing ****

            if (_titleTopicDict.ContainsKey(topic.Title))
            {
                fhir.SubscriptionTopic oldTopic = _titleTopicDict[topic.Title];

                // **** remove if this topic exists in other dictionaries ****

                RemoveIfExists(_localUrlTopicDict, localUrl);
                RemoveIfExists(_canonicalUrlTopicDict, oldTopic.Url);
                RemoveIfExists(_idTopicDict, oldTopic.Title);

                // **** remove from this dict ****

                _titleTopicDict.Remove(topic.Title);
            }

            // **** check for this id already existing ****

            if (_idTopicDict.ContainsKey(topic.Id))
            {
                fhir.SubscriptionTopic oldTopic = _idTopicDict[topic.Id];

                // **** remove if this topic exists in other dictionaries ****

                RemoveIfExists(_localUrlTopicDict, localUrl);
                RemoveIfExists(_canonicalUrlTopicDict, oldTopic.Url);
                RemoveIfExists(_titleTopicDict, oldTopic.Title);

                // **** remove from this dict ****

                _idTopicDict.Remove(topic.Id);
            }

            // **** add to local url dictionary ***

            _localUrlTopicDict.Add(localUrl, topic);

            // **** add to canonical url dictionary ****

            _canonicalUrlTopicDict.Add(topic.Url, topic);

            // **** add to the title dictionary ****

            _titleTopicDict.Add(topic.Title, topic);

            // **** add to id dictionary ****

            _idTopicDict.Add(topic.Id, topic);
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>Attempts to get topic a fhir.SubscriptionTopic from the given string.</summary>
        ///
        /// <remarks>Gino Canessa, 11/5/2019.</remarks>
        ///
        /// <param name="key">  The key for the topic</param>
        /// <param name="topic">[out] The topic.</param>
        ///
        /// <returns>True if it succeeds, false if it fails.</returns>
        ///-------------------------------------------------------------------------------------------------

        public static bool TryGetTopic(string key, out fhir.SubscriptionTopic topic)
        {
            topic = GetTopic(key);

            return(topic != null);
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>Adds or updates a Topic</summary>
        ///
        /// <remarks>Gino Canessa, 6/6/2019.</remarks>
        ///
        /// <param name="topic">The topic.</param>
        ///-------------------------------------------------------------------------------------------------

        public static void AddOrUpdate(fhir.SubscriptionTopic topic)
        {
            _instance._AddOrUpdate(topic);
        }
        /// <summary>Creates a subscription.</summary>
        /// <param name="topic">The topic.</param>
        /// <returns>An asynchronous result that yields true if it succeeds, false if it fails.</returns>
        public static async Task <bool> CreateSubscription(fhir.SubscriptionTopic topic)
        {
            try
            {
                string url = string.IsNullOrEmpty(Configuration["Basic_Public_Url"])
                    ? Configuration["Basic_Internal_Url"]
                    : Configuration["Basic_Public_Url"];

                fhir.Subscription subscription = new Subscription()
                {
                    ChannelType     = SubscriptionChannelType.rest_hook,
                    Endpoint        = url,
                    HeartbeatPeriod = 60,
                    Content         = SubscriptionContentCodes.ID_ONLY,
                    ContentType     = "application/fhir+json",
                    FilterBy        = new SubscriptionFilterBy[]
                    {
                        new SubscriptionFilterBy()
                        {
                            SearchParamName = "patient",
                            SearchModifier  = SubscriptionFilterBySearchModifierCodes.EQUALS,
                            Value           = $"Patient/{_patientId}"
                        },
                    },
                    Topic = new Reference()
                    {
                        reference = topic.Url
                    },
                    Reason = "DevDays Example - C#",
                    Status = SubscriptionStatusCodes.REQUESTED,
                };

                string serialzed = JsonConvert.SerializeObject(
                    subscription,
                    new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver  = _contractResolver,
                });

                // build our request
                HttpRequestMessage request = new HttpRequestMessage()
                {
                    Method     = HttpMethod.Post,
                    RequestUri = GetFhirUri("Subscription"),
                    Headers    =
                    {
                        Accept =
                        {
                            new MediaTypeWithQualityHeaderValue("application/fhir+json")
                        },
                    },
                    Content = new StringContent(
                        serialzed,
                        Encoding.UTF8,
                        "application/fhir+json"
                        ),
                };
                request.Headers.Add("Prefer", "return=representation");

                // make our request
                HttpResponseMessage response = await _restClient.SendAsync(request);

                // check the status code
                if ((response.StatusCode != System.Net.HttpStatusCode.OK) &&
                    (response.StatusCode != System.Net.HttpStatusCode.Created) &&
                    (response.StatusCode != System.Net.HttpStatusCode.Accepted) &&
                    (response.StatusCode != System.Net.HttpStatusCode.NoContent))
                {
                    Console.WriteLine($" Could not Post Subscription: {request.RequestUri.ToString()} returned: {response.StatusCode}");
                    return(false);
                }

                // parse the return
                string body = await response.Content.ReadAsStringAsync();

                fhir.Subscription sub = JsonConvert.DeserializeObject <fhir.Subscription>(body);

                // grab the subscription id so we can clean up
                _subscriptionId = sub.Id;

                // good here
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to Create Subscription: {ex.Message}");
                return(false);
            }
        }