/*
 * Copyright 2017 Crown Copyright
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package stroom.search.solr.search;

import stroom.datasource.api.v2.DataSource;
import stroom.docref.DocRef;
import stroom.event.logging.rs.api.AutoLogged;
import stroom.event.logging.rs.api.AutoLogged.OperationType;
import stroom.query.api.v2.FlatResult;
import stroom.query.api.v2.QueryKey;
import stroom.query.api.v2.SearchRequest;
import stroom.query.api.v2.SearchResponse;
import stroom.query.api.v2.TableResult;
import stroom.query.common.v2.SearchResponseCreator;
import stroom.query.common.v2.SearchResponseCreatorCache;
import stroom.query.common.v2.SearchResponseCreatorManager;
import stroom.search.solr.SolrIndexService;
import stroom.util.logging.LambdaLogger;
import stroom.util.logging.LambdaLoggerFactory;
import stroom.util.logging.LogUtil;

import com.codahale.metrics.annotation.Timed;

import java.util.stream.Collectors;
import javax.inject.Inject;

@AutoLogged
public class StroomSolrIndexQueryResourceImpl implements StroomSolrIndexQueryResource {

    private static final LambdaLogger LOGGER = LambdaLoggerFactory.getLogger(StroomSolrIndexQueryResourceImpl.class);

    private final SearchResponseCreatorManager searchResponseCreatorManager;
    private final SolrIndexService solrIndexService;

    @Inject
    StroomSolrIndexQueryResourceImpl(final SolrSearchResponseCreatorManager searchResponseCreatorManager,
                                     final SolrIndexService solrIndexService) {
        this.searchResponseCreatorManager = searchResponseCreatorManager;
        this.solrIndexService = solrIndexService;
    }

    @Timed
    @Override
    public DataSource getDataSource(final DocRef docRef) {
        return solrIndexService.getDataSource(docRef);
    }

    @Timed
    @Override
    public SearchResponse search(final SearchRequest request) {
        //if this is the first call for this query key then it will create a searchResponseCreator (& store) that have
        //a lifespan beyond the scope of this request and then begin the search for the data
        //If it is not the first call for this query key then it will return the existing searchResponseCreator with
        //access to whatever data has been found so far
        final SearchResponseCreator searchResponseCreator = searchResponseCreatorManager.get(
                new SearchResponseCreatorCache.Key(request));

        //create a response from the data found so far, this could be complete/incomplete
        SearchResponse searchResponse = searchResponseCreator.create(request);

        LOGGER.trace(() ->
                getResponseInfoForLogging(request, searchResponse));

        return searchResponse;
    }

    private String getResponseInfoForLogging(final SearchRequest request, final SearchResponse searchResponse) {
        String resultInfo;

        if (searchResponse.getResults() != null) {
            resultInfo = "\n" + searchResponse.getResults().stream()
                    .map(result -> {
                        if (result instanceof FlatResult) {
                            FlatResult flatResult = (FlatResult) result;
                            return LogUtil.message(
                                    "  FlatResult - componentId: {}, size: {}, ",
                                    flatResult.getComponentId(),
                                    flatResult.getSize());
                        } else if (result instanceof TableResult) {
                            TableResult tableResult = (TableResult) result;
                            return LogUtil.message(
                                    "  TableResult - componentId: {}, rows: {}, totalResults: {}, " +
                                            "resultRange: {}",
                                    tableResult.getComponentId(),
                                    tableResult.getRows().size(),
                                    tableResult.getTotalResults(),
                                    tableResult.getResultRange());
                        } else {
                            return "  Unknown type " + result.getClass().getName();
                        }
                    })
                    .collect(Collectors.joining("\n"));
        } else {
            resultInfo = "null";
        }

        return LogUtil.message("Return search response, key: {}, result sets: {}, " +
                        "complete: {}, errors: {}, results: {}",
                request.getKey().toString(),
                searchResponse.getResults(),
                searchResponse.complete(),
                searchResponse.getErrors(),
                resultInfo);
    }

    @Timed
    @Override
    @AutoLogged(OperationType.UNLOGGED)
    public Boolean destroy(final QueryKey queryKey) {
        searchResponseCreatorManager.remove(new SearchResponseCreatorCache.Key(queryKey));
        return Boolean.TRUE;
    }
}

@@ -1126,68 +1126,8 @@
 he;%0A
-import stroom.query.common.v2.SearchResponseCreatorManager;%0A
 impo
@@ -1403,16 +1403,88 @@
 Inject;%0A
+import javax.inject.Provider;%0Aimport javax.inject.Singleton;%0A%0A@Singleton
 %0A@AutoLo
@@ -1710,24 +1710,37 @@
 ivate final 
+Provider%3CSolr
 SearchRespon
@@ -1747,32 +1747,33 @@
 seCreatorManager
+%3E
  searchResponseC
@@ -1781,24 +1781,32 @@
 eatorManager
+Provider
 ;%0A    privat
@@ -1809,24 +1809,33 @@
 ivate final 
+Provider%3C
 SolrIndexSer
@@ -1830,32 +1830,33 @@
 SolrIndexService
+%3E
  solrIndexServic
@@ -1856,16 +1856,24 @@
 xService
+Provider
 ;%0A%0A    @
@@ -1918,24 +1918,33 @@
 eImpl(final 
+Provider%3C
 SolrSearchRe
@@ -1963,16 +1963,62 @@
 rManager
+%3E%0A                                            
  searchR
@@ -2038,16 +2038,24 @@
 rManager
+Provider
 ,%0A      
@@ -2091,16 +2091,25 @@
   final 
+Provider%3C
 SolrInde
@@ -2116,16 +2116,17 @@
 xService
+%3E
  solrInd
@@ -2134,16 +2134,24 @@
 xService
+Provider
 ) %7B%0A    
@@ -2187,16 +2187,24 @@
 rManager
+Provider
  = searc
@@ -2226,16 +2226,24 @@
 rManager
+Provider
 ;%0A      
@@ -2265,16 +2265,24 @@
 xService
+Provider
  = solrI
@@ -2292,16 +2292,24 @@
 xService
+Provider
 ;%0A    %7D%0A
@@ -2424,16 +2424,30 @@
 xService
+Provider.get()
 .getData
@@ -3031,21 +3031,30 @@
 rManager
+Provider
 .get(
+)
 %0A       
@@ -3062,16 +3062,21 @@
         
+.get(
 new Sear
@@ -5537,16 +5537,30 @@
 rManager
+Provider.get()
 .remove(

Use providers and apply @Singleton annotation