private void FinalizeResponse(SolrWebRequest request)
        {
            var responce = Client.Execute(request);

            if (responce.StatusCode == HttpStatusCode.OK || responce.StatusCode == HttpStatusCode.NoContent)
            {
                LastResponse = new LinqToSolrResponse {
                    LastServiceUri = responce.ResponseUri
                };
                return;
            }

            if (!string.IsNullOrEmpty(responce.Content))
            {
                LastResponse = JsonConvert.DeserializeObject <LinqToSolrResponse>(responce.Content);
                LastResponse.LastServiceUri = responce.ResponseUri;
                LastResponse.Content        = responce.Content;
            }

            if (LastResponse.Error != null)
            {
                throw new Exception("Oops! SOLR Says: " + LastResponse.Error.Message);
            }
        }
        public object Query(Type elementType, LinqToSolrQuery query = null)
        {
            if (query != null)
            {
                CurrentQuery = query;
            }
            var index = Configuration.GetIndex(elementType);

            if (string.IsNullOrEmpty(index))
            {
                throw new ArgumentNullException(nameof(index),
                                                string.Format(
                                                    "The type '{0}' is not assigned for any Solr Index. Register this type in a service configuration (SolrRequestConfiguration.MapIndexFor)",
                                                    ElementType.Name));
            }

            if (!string.IsNullOrEmpty(Configuration.SolrLogin) && !string.IsNullOrEmpty(Configuration.SolrPassword))
            {
                //   Client.Authenticator = new HttpBasicAuthenticator(Configuration.SolrLogin, Configuration.SolrPassword);
            }

            var response = Client.Execute(PrepareQueryRequest(index));

            LastResponse = new LinqToSolrResponse();
            LastResponse.LastServiceUri = response.ResponseUri;

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                throw new Exception("Server returned 404 - Not Found. Check if solr url is correct or index name was correctly provided.");
            }

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new UnauthorizedAccessException(
                          "Solr is protected by password. Setup login and passowrd in the configuration class.");
            }

            if (response.ErrorException != null)
            {
                throw response.ErrorException;
            }

            LastResponse = JsonConvert.DeserializeObject <LinqToSolrResponse>(response.Content, new LinqToSolrRawJsonConverter());

            LastResponse.LastServiceUri = response.ResponseUri;
            if (LastResponse.Header.Status == 0)
            {
                if (LastResponse.Body != null)
                {
                    LastResponse.FoundDocuments = (int)LastResponse.Body?.Count;

                    var listMethod =
                        typeof(List <>).MakeGenericType(CurrentQuery.Select != null && !CurrentQuery.Select.IsSingleField
                            ? CurrentQuery.Select.Type
                            : elementType);

                    var genList = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(LastResponse.Body.Documents), listMethod,
                                                                new JsonSerializerSettings {
                        Error = ErrorHandler, Converters = new List <JsonConverter> {
                            new LinqToSolrRawJsonConverter()
                        }
                    }) as IEnumerable;
                    LastResponse.Body.Documents = genList.Cast <object>().ToList();



                    if (LastResponse.Facets != null)
                    {
                        foreach (var facet in CurrentQuery.Facets)
                        {
                            var content = JsonConvert.DeserializeObject <JObject>(response.Content)["facet_counts"];
                            var groups  = content["facet_fields"][facet.SolrName] as JArray;

                            LastResponse.Facets.Add(facet.SolrName,
                                                    groups.Where((x, i) => i % 2 == 0).Select(x => ((JValue)x).Value).ToArray());
                        }
                    }

                    if (CurrentQuery.Select?.IsSingleField == true)
                    {
                        var fieldDelegate = ((LambdaExpression)CurrentQuery.Select.Expression).Compile();

#if PORTABLE || NETCORE
                        var selectMethod = typeof(Enumerable).GetRuntimeMethods().First(m => m.Name == "Select" && m.GetParameters().Count() == 2);
#else
                        var selectMethod = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).First(m => m.Name == "Select" && m.GetParameters().Count() == 2);
#endif
                        var fieldList = selectMethod.MakeGenericMethod(elementType, CurrentQuery.Select.Type)
                                        .Invoke(genList, new object[] { genList, fieldDelegate });
                        CurrentQuery = null;
                        return(fieldList);
                    }

                    CurrentQuery = null;
                    return(genList);
                }


                if (CurrentQuery.IsGroupEnabled)
                {
#if PORTABLE || NETCORE
                    var args = ElementType.GetTypeInfo().IsGenericTypeDefinition
                        ? ElementType.GetTypeInfo().GenericTypeParameters
                        : ElementType.GetTypeInfo().GenericTypeArguments;
                    var _keyType   = args[0];
                    var _valueType = args[1];
#else
                    var _keyType   = ElementType.GetGenericArguments()[0];
                    var _valueType = ElementType.GetGenericArguments()[1];
#endif

                    var solrConverterType = typeof(LinqToSolrGroupingResponseConverter <,>).MakeGenericType(_keyType, _valueType);
                    var converterInstance = Activator.CreateInstance(solrConverterType);

                    var groupResult = JsonConvert.DeserializeObject(response.Content, solrConverterType,
                                                                    converterInstance as JsonConverter);
                    return(groupResult);
                }


                CurrentQuery = null;
                return(null);
            }
            throw new Exception(LastResponse.Error.Message);
        }