/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.brooklyn.entity.nosql.elasticsearch;

import static com.google.common.base.Preconditions.checkNotNull;

import org.apache.brooklyn.api.sensor.AttributeSensor;
import org.apache.brooklyn.core.location.access.BrooklynAccessUtils;
import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
import org.apache.brooklyn.feed.http.HttpFeed;
import org.apache.brooklyn.feed.http.HttpPollConfig;
import org.apache.brooklyn.feed.http.HttpValueFunctions;
import org.apache.brooklyn.feed.http.JsonFunctions;
import org.apache.brooklyn.util.http.HttpToolResponse;
import org.apache.brooklyn.util.guava.Functionals;
import org.apache.brooklyn.util.guava.Maybe;
import org.apache.brooklyn.util.guava.MaybeFunctions;
import org.apache.brooklyn.util.guava.TypeTokens;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.net.HostAndPort;
import com.google.gson.JsonElement;

public class ElasticSearchNodeImpl extends SoftwareProcessImpl implements ElasticSearchNode {
    
    protected static final Function<Maybe<JsonElement>, Maybe<JsonElement>> GET_FIRST_NODE_FROM_NODES = new Function<Maybe<JsonElement>, Maybe<JsonElement>>() {
        @Override public Maybe<JsonElement> apply(Maybe<JsonElement> input) {
            if (input.isAbsent()) {
                return input;
            }
            return Maybe.fromNullable(input.get().getAsJsonObject().entrySet().iterator().next().getValue());
        }
    };
    
    protected static final Function<HttpToolResponse, Maybe<JsonElement>> GET_FIRST_NODE = Functionals.chain(HttpValueFunctions.jsonContents(), 
            MaybeFunctions.<JsonElement>wrap(), JsonFunctions.walkM("nodes"), GET_FIRST_NODE_FROM_NODES);
    
    
    HttpFeed httpFeed;

    @Override
    public Class<ElasticSearchNodeDriver> getDriverInterface() {
        return ElasticSearchNodeDriver.class;
    }
    
    protected static final <T> HttpPollConfig<T> getSensorFromNodeStat(AttributeSensor<T> sensor, String... jsonPath) {
        return new HttpPollConfig<T>(sensor)
            .onSuccess(Functionals.chain(GET_FIRST_NODE, JsonFunctions.walkM(jsonPath), JsonFunctions.castM(TypeTokens.getRawRawType(sensor.getTypeToken()), null)))
            .onFailureOrException(Functions.<T>constant(null));
    }
    
    @Override
    protected void connectSensors() {
        super.connectSensors();
        Integer rawPort = getAttribute(HTTP_PORT);
        String hostname = getAttribute(HOSTNAME);
        checkNotNull(rawPort, "HTTP_PORT sensors not set for %s; is an acceptable port available?", this);

        HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, rawPort);
        Function<Maybe<JsonElement>, String> getNodeId = new Function<Maybe<JsonElement>, String>() {
            @Override public String apply(Maybe<JsonElement> input) {
                if (input.isAbsent()) {
                    return null;
                }
                return input.get().getAsJsonObject().entrySet().iterator().next().getKey();
            }
        };

        sensors().set(DATASTORE_URL, String.format("http://%s", hp));
        if (isHttpMonitoringEnabled()) {
            boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

            httpFeed = HttpFeed.builder()
                    .entity(this)
                    .period(1000)
                    .baseUri(String.format("http://%s:%s/_nodes/_local/stats", hp.getHostText(), hp.getPort()))
                    .poll(new HttpPollConfig<Boolean>(SERVICE_UP)
                        .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                        .onFailureOrException(Functions.constant(false)))
                    .poll(new HttpPollConfig<String>(NODE_ID)
                        .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), MaybeFunctions.<JsonElement>wrap(), JsonFunctions.walkM("nodes"), getNodeId))
                        .onFailureOrException(Functions.constant("")))
                    .poll(new HttpPollConfig<String>(CLUSTER_NAME)
                            .onSuccess(HttpValueFunctions.jsonContents("cluster_name", String.class)))
                    .poll(getSensorFromNodeStat(NODE_NAME, "name"))
                    .poll(getSensorFromNodeStat(DOCUMENT_COUNT, "indices", "docs", "count")
                            .enabled(retrieveUsageMetrics))
                    .poll(getSensorFromNodeStat(STORE_BYTES, "indices", "store", "size_in_bytes")
                            .enabled(retrieveUsageMetrics))
                    .poll(getSensorFromNodeStat(GET_TOTAL, "indices", "get", "total")
                            .enabled(retrieveUsageMetrics))
                    .poll(getSensorFromNodeStat(GET_TIME_IN_MILLIS, "indices", "get", "time_in_millis")
                            .enabled(retrieveUsageMetrics))
                    .poll(getSensorFromNodeStat(SEARCH_QUERY_TOTAL, "indices", "search", "query_total")
                            .enabled(retrieveUsageMetrics))
                    .poll(getSensorFromNodeStat(SEARCH_QUERY_TIME_IN_MILLIS, "indices", "search", "query_time_in_millis")
                            .enabled(retrieveUsageMetrics))
                    .build();
        } else {
            connectServiceUpIsRunning();
        }
    }
    
    @Override
    protected void disconnectSensors() {
        if (httpFeed != null) {
            httpFeed.stop();
        }
        disconnectServiceUpIsRunning();
        super.disconnectSensors();
    }
    
    protected boolean isHttpMonitoringEnabled() {
        return Boolean.TRUE.equals(getConfig(USE_HTTP_MONITORING));
    }
}
