public List<Facility> Search(Location loc, FacilityType type)
        {

            string serviceCategory = null;
            string servicetype = null;
            switch (type)
            {
                case FacilityType.GP:
                    serviceCategory = "General Practice/GP (doctor)";
                    break;
                case FacilityType.Pharmacy:
                    servicetype = "Pharmacy";
                    break;
            }

            var requestDic = new Dictionary<string, string>
            {
                {"usepostcoderadialsearch", "true"},
                {"suburbpostcodedata", JsonConvert.SerializeObject(new { SiteSearchSuburbPostcodeParams = new { SuburbPostcode = loc.Suburb + " " + loc.Postcode, SearchSurroundingSuburbs = true } })},
                {"startpos", "1"},
                {"servicetype", servicetype},
                {"ServiceCategory", serviceCategory},
                {"SearchSiteAddress", "true"},
                {"SearchServiceCoverageArea", "false"},
                {"SearchServiceAddress", "false"},
                {"orderby", "Distance"},
                {"endpos", "5"},
                {"deliverymethod", "{\"string\":\"Site Visit\"}"},
                {"callback", "angular.callbacks._4"},
                {"apikey", "nhccn-9vSRwUZooHY2BebTOvAhA93n"},
                {"alwaysreturn", "5"}
            };

            string url = "https://api.nhsd.com.au/nhsd/v2.8/rest/sitesearch?";
            foreach (var entry in requestDic)
            {
                if (entry.Value != null)
                {
                    url += entry.Key + "=" + Uri.EscapeDataString(entry.Value) + "&";
                }
            }

            WebRequest req = WebRequest.Create(url);

            StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());
            WebResponse response = req.GetResponse();
            string responseString = sr.ReadToEnd();
            string json = responseString.Substring(requestDic["callback"].Length + 1, responseString.Length - requestDic["callback"].Length - 2);
            RootObject result = JsonConvert.DeserializeObject<RootObject>(json);
            FacilitySearchResult searchResult = new FacilitySearchResult();
            var firstSite = result.SiteSearchResponse.SiteSearchResult.ResultList.SiteData[0];
            
            var facilities = result.SiteSearchResponse.SiteSearchResult.ResultList.SiteData.Select(a => new Facility
                {
                    Location = new Location
                    {
                        Address = a.SiteAddress.Address_Line_1 + " " + a.SiteAddress.Address_Line_2 + " " + a.SiteAddress.Address_Line_3,
                        Suburb = a.SiteAddress.Suburb,
                        Postcode = a.SiteAddress.Postcode,
                        Latitude = a.SiteAddress.Latitude,
                        Longitude = a.SiteAddress.Longitude,
                    },
                    OpenNow = a.ServiceCollection.ServiceData.OpenNow,
                    ClosingTime = GetClosingTime(a.ServiceCollection.ServiceData),
                    Name = a.OrganisationName,
                }).ToList();
            return facilities;
        }
        public FacilitySearchResult Get(string latitude, string longitude, string gender, bool isChild, FacilityType type)
        {
            FacilitySearchResult result = new FacilitySearchResult();

            result.Origin = new Location { Latitude = latitude, Longitude = longitude };

            // Get the suburb and postcode for the origin location
            var google = new HealthBuddy.Api.Directions.DirectionsService();
            google.Lookup(result.Origin);
            double lat = double.Parse(result.Origin.Latitude);
            double lng = double.Parse(result.Origin.Longitude);

            if (type == FacilityType.Hospital)
            {
                // Use GovHack data sets - my hospitals contact list, length of stay data, etc.

                var hospitals = db.myhospitals_contact_data
                    .Where(
                        a => (!a.Emergency.HasValue || a.Emergency.Value)
                        && (!a.Child.HasValue || a.Child == isChild)
                        && (a.Gender == null || a.Gender == gender))
                    .OrderBy(
                        a => (a.Latitude - lat) * (a.Latitude - lat)
                        + (a.Longitude - lng) * (a.Longitude - lng))
                    .Take(5).ToList();

                var ids = hospitals.Select(a => a.Id).ToArray();
                var codes = hospitals.Select(a => a.HospitalCode).ToArray();
                var lengthsOfStay = db.emergencydept4hourlengthofstaymetadata.Where(a => ids.Contains(a.MyHospitalsId.Value)).OrderBy(a => a.ID).ToList();
                var emergencyStats = db.ED001_HospitalStatus.Where(a => codes.Contains(a.HospitalCode)).OrderBy(a => a.Id).ToList();

                result.Facilities.AddRange(hospitals.Select(hosp => new Facility
                    {
                        Name = hosp.Hospital_name,
                        LessThan4HrsPct = GetLengthOfStay(hosp, lengthsOfStay),
                        EmergencyDepartmentStatus = GetEDStatus(hosp, emergencyStats),
                        Location = GetLocation(hosp),
                        TwitterSentiment = EventHub.EventService.GetTwitterSentiment(hosp.HospitalCode),
                        OpenNow = "true",
                    }));
            }
            else if (type == FacilityType.Community)
            {
                // Use ACHC20150617_DataDotGov

                var charities = db.ACHC20150617_DataDotGov
                    .Where(
                        a => (a.Advancing_Health == "Y")
                        && (!isChild || a.Children == "Y")
                        && (a.Latitude.HasValue && a.Longitude.HasValue))
                    .OrderBy(
                        a => (a.Latitude - lat) * (a.Latitude - lat)
                        + (a.Longitude - lng) * (a.Longitude - lng))
                    .Take(5).ToList();

                result.Facilities.AddRange(charities.Select(hosp => new Facility
                {
                    Name = hosp.Charity_Legal_Name,
                    Location = GetLocation(hosp)
                }));
            }
            else
            {
                // Use NHSD lookup.
                var nhsd = new HealthBuddy.Api.Nhsd.NhsdService();
                result.Facilities.AddRange(nhsd.Search(result.Origin, type));
            }

            // Get the travel times by driving and transit to each facility.
            foreach (var facility in result.Facilities)
            {
                facility.TravelTimes = google.GetTravelTimes(result.Origin, facility.Location);
            }
            return result;
        }