public ICollection <ISolrQuery> BuildFilterQueries(SearchParam parameters)
        {
            var queriesFromFacets = from p in parameters.Facets
                                    select(ISolrQuery) Query.Field(p.Key).Is(p.Value);



            List <ISolrQuery> filter = new List <ISolrQuery>();

            filter = queriesFromFacets.ToList();
            //    parameters.PickUpDateSearch = Convert.ToDateTime("2015-01-10 04:33:41.040"); //to be taken out later
            var Day1 = new SolrQueryByRange <DateTime>("PickUpTime", Common.AbsoluteStart(parameters.PickUpDateSearch), Common.AbsoluteEnd(parameters.PickUpDateSearch.AddDays(90)));

            filter.Add((ISolrQuery)Day1);

            return(filter);
        }
        public ActionResult Index(SearchParam parameters)
        {
            if (TempData["ErrorMessage"] != null)
            {
                ViewBag.ErrorMessage = TempData["ErrorMessage"];
            }
            else
            {
                ViewBag.ErrorMessage = "";
            }
            var ChangeLocation = HttpContext.Request.QueryString["ChangeLocation"];

            if ((ChangeLocation != null) && (ChangeLocation != ""))
            {
                GLatLong loc = new GLatLong();
                loc = GeoCodingHelper.GetLatLong(ChangeLocation.ToString());


                if (loc != null)
                {
                    Session["UserLocLat"]  = loc.Latitude;
                    Session["UserLocLong"] = loc.Longitude;
                }
                Session["UserLoc"] = ChangeLocation;
            }
            else
            {
                var LocationsSearched = dbmeals.LocationsSearcheds.Where(x => x.UserID == WebSecurity.CurrentUserId).OrderByDescending(x => x.DateCreated).ToList().FirstOrDefault();
                if (LocationsSearched != null)
                {
                    Session["UserLoc"]          = LocationsSearched.Location;
                    parameters.FreeSearch       = LocationsSearched.Keywords;
                    Session["UserLocLat"]       = LocationsSearched.Latitude;
                    Session["UserLocLong"]      = LocationsSearched.Longitude;
                    parameters.DistanceSearch   = LocationsSearched.Distance.HasValue ? LocationsSearched.Distance.Value.ToString() : string.Empty;
                    parameters.PickUpDateSearch = Common.AbsoluteEnd(LocationsSearched.DateRangeStart.HasValue ? LocationsSearched.DateRangeStart.Value : DateTime.Now);// LocationsSearched.DateRangeStart;
                    //parameters.DateRangeEnd = LocationsSearched.DateRangeEnd;
                }
            }


            if (String.IsNullOrEmpty(parameters.DistanceSearch))
            {
                parameters.DistanceSearch = "100";
            }

            if (parameters.PickUpDateSearch == null)
            {
                parameters.PickUpDateSearch = DateTime.Now;
            }



            string pointofreference = Session["UserLocLat"] + "," + Session["UserLocLong"];

            LocationsSearched ls = new LocationsSearched();

            ls.Location       = Convert.ToString(Session["UserLoc"]);//.ToString();
            ls.Keywords       = parameters.FreeSearch;
            ls.Latitude       = Convert.ToDecimal(Session["UserLocLat"]);
            ls.Longitude      = Convert.ToDecimal(Session["UserLocLong"]);
            ls.DateRangeStart = Common.AbsoluteStart(parameters.PickUpDateSearch);
            ls.DateRangeEnd   = Common.AbsoluteEnd(parameters.PickUpDateSearch);
            ls.Distance       = Convert.ToInt32(parameters.DistanceSearch);
            ls.DistanceUnit   = "km";
            ls.DateCreated    = DateTime.Now;
            ls.UserID         = WebSecurity.CurrentUserId;
            try
            {
                dbmeals.LocationsSearcheds.Add(ls);
                dbmeals.SaveChanges();
            }
            catch (Exception e)
            {
                string message = e.Message;
            }
            try
            {
                ICollection <ISolrFacetQuery> list =
                    AllFacetFields.Except(SelectedFacetFields(parameters)).
                    Select(f => new SolrFacetFieldQuery(f)
                {
                    MinCount = 1
                })
                    .Cast <ISolrFacetQuery>().ToList();



                var start = (parameters.PageIndex - 1) * parameters.PageSize;

                var matchingProducts = solr.Query(BuildQuery(parameters), new QueryOptions
                {
                    FilterQueries = BuildFilterQueries(parameters),
                    Rows          = parameters.PageSize,
                    Start         = start,
                    OrderBy       = GetSelectedSort(parameters),
                    SpellCheck    = new SpellCheckingParameters(),
                    Facet         = new FacetParameters
                    {
                        Queries = list
                    },


                    ExtraParams = new Dictionary <string, string>
                    {
                        // uncomment for filtering by distance
                        { "fq", "{!geofilt}" },
                        { "d", parameters.DistanceSearch },         // distance.ToString(CultureInfo.InvariantCulture)} replace distance with your radius filter
                        { "sfield", "latlng" },                     // replace lat_long with your field in solr that stores the lat long values
                        { "pt", pointofreference },                 // this is the point of reference
                        // {"sort","geodist() asc"},
                        { "fl", "*,Distance:geodist()" },
                    }
                });

                var distancemodel = new DistanceViewModel();


                // var matchingProducts

                var ProductModel = new ProductView
                {
                    WholeSet   = matchingProducts,
                    Search     = parameters,
                    TotalCount = matchingProducts.NumFound,
                    Facets     = matchingProducts.FacetFields,
                    //  PickUpTimeFacet = GetPickUpTimeFacet(matchingProducts.FacetQueries),
                    // DistanceFacet = GetDistanceFacet(matchingProducts.FacetQueries),
                    DidYouMean = GetSpellCheckingResult(matchingProducts),
                    //DistanceLimitList.SelectedDistance = parameters.DistanceLimit
                };


                // Preselect the option with Value = "US"
                // Make sure you have such option in the Countries list


                List <SolrResultSet> SolrResultSetList = new List <SolrResultSet>();
                SolrResultSetList = (from n in ProductModel.WholeSet
                                     select n).ToList();

                var ProductViewModel = new ResultSetViewModel();
                ProductViewModel.Search       = ProductModel.Search;
                ProductViewModel.TotalCount   = ProductModel.TotalCount;
                ProductViewModel.Facets       = ProductModel.Facets;
                ProductViewModel.DidYouMean   = ProductModel.DidYouMean;
                ProductViewModel.ProviderList = (from n in SolrResultSetList
                                                 group n by new
                {
                    n.ProviderName,
                    n.ProviderType
                    ,
                    n.Distance,
                    n.latlng,
                    n.PhoneNumber,
                    n.FullAddress,
                    n.Cuisine
                } into g
                                                 select new Provider()
                {
                    ProviderName = g.Key.ProviderName,
                    ProviderType = g.Key.ProviderType,
                    Distance = g.Key.Distance,
                    latlng = g.Key.latlng,
                    PhoneNumber = g.Key.PhoneNumber,
                    FullAddress = g.Key.FullAddress,
                    Cuisine = g.Key.Cuisine,
                }).ToList();

                foreach (Provider p in ProductViewModel.ProviderList)
                {
                    p.Products = (from n in SolrResultSetList
                                  where n.ProviderName == p.ProviderName
                                  select new Product()

                    {
                        MealAdID = n.MealAdID,
                        MealItemName = n.MealItemName,
                        FoodType = n.FoodType,
                        MealType = n.MealType,
                        Price = n.Price,
                        Ingredients = n.Ingredients,
                        AllergenicIngredients = n.AllergenicIngredients,
                        Timestamp = n.Timestamp,
                        Description = n.Description
                    }).ToList();
                }


                distancemodel.SelectedDistanceLimit = parameters.DistanceSearch;
                ProductViewModel.DistanceDD         = distancemodel;

                return(View(ProductViewModel));
            }
            catch (SolrConnectionException e)
            {
                string msg = e.Message;
                return(View(new ResultSetViewModel
                {
                    QueryError = true,
                }));
            }
        }