package com.oneops.search.msg.processor;

import com.google.gson.JsonParser;
import com.oneops.cms.dj.domain.CmsRelease;
import com.oneops.search.msg.index.Indexer;
import org.apache.http.client.fluent.Request;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/*******************************************************************************
 *
 *   Copyright 2016 Walmart, Inc.
 *
 *   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.
 *
 *******************************************************************************/

@Service
public class ReleaseMessageProcessor implements MessageProcessor {
    private static Logger logger = Logger.getLogger(ReleaseMessageProcessor.class);
    @Autowired
    private Indexer indexer;
    @Value("${designSnapshotURL}")
    private String designSnapshotURL;
    @Value("${manifestSnapshotURL}")
    private String manifestSnapshotURL;
    private static final String RELEASE = "release";

    @Override
    public void processMessage(String message, String msgType, String msgId) {
        CmsRelease release = GSON.fromJson(message, CmsRelease.class);
        String releaseMsg = GSON_ES.toJson(release);
        indexer.indexEvent(RELEASE, releaseMsg);
        indexer.index(String.valueOf(release.getReleaseId()), RELEASE, releaseMsg);
        indexSnapshot(release);
    }

    private void indexSnapshot(CmsRelease release) {
        try {
            if (!"closed".equalsIgnoreCase(release.getReleaseState())) {
                logger.info("Release is not closed. Won't do snapshot");
                return;
            }
            if (release.getNsPath().endsWith("bom")) return; // ignore bom release

            String url = (release.getNsPath().endsWith("manifest") ? manifestSnapshotURL : designSnapshotURL) + release.getNsPath();  // set snapshot URL based on release type
            logger.info("Retrieving snapshot for:" + url + " expected release:" + release.getReleaseId());
            String message = Request.Get(url).addHeader("Content-Type", "application/json").execute().returnContent().asString();
            long releaseId = new JsonParser().parse(message).getAsJsonObject().get("release").getAsLong();
            if (releaseId > release.getReleaseId()) {
                logger.warn("Snapshot is dirty, so discarding. Was expecting release:" + release.getReleaseId() + " snapshot has rfcs from release:" + releaseId);
            } else {
                indexer.index(String.valueOf(release.getReleaseId()), "snapshot", message);
                logger.info("Snapshot indexed for release ID: " + release.getReleaseId());
            }

        } catch (Exception e) {
            logger.error("Error while retrieving snapshot" + e.getMessage(), e);
        }
    }
}

@@ -251,164 +251,615 @@
 org.
-springframework.beans.factory.annotation.Autowired;%0Aimport org.springframework.beans.factory.annotation.Value;%0Aimport org.springframework.stereotype.Service
+elasticsearch.action.search.SearchResponse;%0Aimport org.elasticsearch.action.search.SearchType;%0Aimport org.elasticsearch.client.Client;%0Aimport org.elasticsearch.common.unit.TimeValue;%0Aimport org.elasticsearch.index.query.QueryBuilders;%0Aimport org.springframework.beans.factory.annotation.Autowired;%0Aimport org.springframework.beans.factory.annotation.Value;%0Aimport org.springframework.stereotype.Service;%0A%0Aimport java.util.Calendar;%0Aimport java.util.GregorianCalendar;%0A%0Aimport static org.elasticsearch.index.query.QueryBuilders.boolQuery;%0Aimport static org.elasticsearch.index.query.QueryBuilders.disMaxQuery
 ;%0A%0A/
@@ -1713,16 +1713,71 @@
 essor %7B%0A
+    private static final String SNAPSHOT = %22snapshot%22;%0A
     priv
@@ -1856,23 +1856,8 @@
 s);%0A
-    @Autowired%0A
     
@@ -1864,16 +1864,22 @@
 private 
+final 
 Indexer 
@@ -1887,16 +1887,49 @@
 ndexer;%0A
+    private final Client client;%0A
     @Val
@@ -2124,16 +2124,169 @@
 ease%22;%0A%0A
+    @Autowired%0A    public ReleaseMessageProcessor(Indexer indexer, Client client) %7B%0A        this.indexer = indexer;%0A        this.client = client;%0A    %7D%0A%0A
     @Ove
@@ -2715,24 +2715,40 @@
  release) %7B%0A
+      %0A        %0A
         try 
@@ -3017,16 +3017,872 @@
 elease%0A%0A
+%0A            Calendar cal = new GregorianCalendar();%0A            cal.add(Calendar.WEEK_OF_YEAR, -2);%0A            long snapshotTimestamp = cal.getTime().getTime();%0A            long hits = client.prepareSearch(%22cms-201*%22)%0A                    .setSearchType(SearchType.COUNT)%0A                    .setTypes(SNAPSHOT)%0A                    .setQuery( boolQuery()%0A                            .must(QueryBuilders.rangeQuery(%22timestamp%22).from(snapshotTimestamp))%0A                            .must(QueryBuilders.termQuery(%22namespace.keyword%22, release.getNsPath()))%0A                    )%0A                    .execute().actionGet().getHits().getTotalHits();%0A            logger.info(%22hits:%22+ hits);%0A            if (hits%3E0) %7B%0A                logger.info(%22there was a snapshot done recently, so won'd do another one. %22);%0A                return;%0A            %7D%0A            %0A
         
@@ -4701,26 +4701,24 @@
 eId()), 
-%22snapshot%22
+SNAPSHOT
 , messag
@@ -4946,20 +4946,29 @@
 ;%0A        %7D%0A
+        %0A
     %7D%0A%7D%0A

fix for