/*
 * 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.servicecomb.foundation.vertx.metrics;

import org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultClientEndpointMetric;
import org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultClientEndpointMetricManager;
import org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultHttpSocketMetric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.impl.HttpClientImpl;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.net.impl.SocketAddressImpl;
import io.vertx.core.spi.metrics.HttpClientMetrics;

/**
 * important: not singleton, every HttpClient instance relate to a HttpClientMetrics instance
 */
public class DefaultHttpClientMetrics implements
    HttpClientMetrics<DefaultHttpSocketMetric, Object, DefaultHttpSocketMetric, DefaultClientEndpointMetric, Object> {

  private static final Logger LOGGER = LoggerFactory.getLogger(DefaultHttpClientMetrics.class);

  private final DefaultClientEndpointMetricManager clientEndpointMetricManager;

  private final HttpClient client;

  private final HttpClientOptions options;

  public DefaultHttpClientMetrics(DefaultClientEndpointMetricManager clientEndpointMetricManager,
      HttpClient client, HttpClientOptions options) {
    this.clientEndpointMetricManager = clientEndpointMetricManager;
    this.client = client;
    this.options = options;
  }

  public HttpClient getClient() {
    return client;
  }

  public HttpClientOptions getOptions() {
    return options;
  }

  @Override
  public DefaultClientEndpointMetric createEndpoint(String host, int port, int maxPoolSize) {
    SocketAddress address = new SocketAddressImpl(port, host);
    return clientEndpointMetricManager.getOrCreateClientEndpointMetric(address);
  }

  @Override
  public void closeEndpoint(String host, int port, DefaultClientEndpointMetric endpointMetric) {
    endpointMetric.decRefCount();
  }

  @Override
  public Object enqueueRequest(DefaultClientEndpointMetric endpointMetric) {
    return null;
  }

  @Override
  public void dequeueRequest(DefaultClientEndpointMetric endpointMetric, Object taskMetric) {
  }

  @Override
  public void endpointConnected(DefaultClientEndpointMetric endpointMetric, DefaultHttpSocketMetric socketMetric) {
    //only http1.1 will invoke this method, just make a check
    if (endpointMetric != null) {
      if (endpointMetric != socketMetric.getEndpointMetric()) {
        socketMetric.setEndpointMetric(endpointMetric);
      }
      endpointMetric.onConnect();
    }
  }

  @Override
  public void endpointDisconnected(DefaultClientEndpointMetric endpointMetric, DefaultHttpSocketMetric socketMetric) {
    endpointMetric.onDisconnect();
    socketMetric.setConnected(false);
  }

  @Override
  public DefaultHttpSocketMetric requestBegin(DefaultClientEndpointMetric endpointMetric,
      DefaultHttpSocketMetric socketMetric, SocketAddress localAddress, SocketAddress remoteAddress,
      HttpClientRequest request) {
    socketMetric.requestBegin();
    return socketMetric;
  }

  @Override
  public void requestEnd(DefaultHttpSocketMetric requestMetric) {
    requestMetric.requestEnd();
  }

  @Override
  public void responseBegin(DefaultHttpSocketMetric requestMetric, HttpClientResponse response) {
  }

  @Override
  public DefaultHttpSocketMetric responsePushed(DefaultClientEndpointMetric endpointMetric,
      DefaultHttpSocketMetric socketMetric,
      SocketAddress localAddress,
      SocketAddress remoteAddress, HttpClientRequest request) {
    return null;
  }

  @Override
  public void requestReset(DefaultHttpSocketMetric requestMetric) {
  }

  @Override
  public void responseEnd(DefaultHttpSocketMetric requestMetric, HttpClientResponse response) {
  }

  @Override
  public Object connected(DefaultClientEndpointMetric endpointMetric, DefaultHttpSocketMetric socketMetric,
      WebSocket webSocket) {
    return null;
  }

  @Override
  public void disconnected(Object webSocketMetric) {

  }

  @Override
  public DefaultHttpSocketMetric connected(SocketAddress remoteAddress, String remoteName) {

    DefaultHttpSocketMetric socketMetric = new DefaultHttpSocketMetric(null);
    try {
      DefaultHttpClientMetrics clientMetrics = (DefaultHttpClientMetrics) ((HttpClientImpl) client).getMetrics();
      DefaultClientEndpointMetric clientEndpointMetric = clientMetrics.clientEndpointMetricManager
          .getClientEndpointMetricMap().get(remoteAddress);
      // set endPointMetric when use http2
      socketMetric.setEndpointMetric(clientEndpointMetric);
    } catch (Exception e) {
      LOGGER.warn("if you use http2, there may cause a null pointer exception. {}/{}", remoteAddress, remoteName);
    }
    return socketMetric;
  }

  @Override
  public void disconnected(DefaultHttpSocketMetric socketMetric, SocketAddress remoteAddress) {
  }

  @Override
  public void bytesRead(DefaultHttpSocketMetric socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
    socketMetric.getEndpointMetric().addBytesRead(numberOfBytes);
  }

  @Override
  public void bytesWritten(DefaultHttpSocketMetric socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
    socketMetric.getEndpointMetric().addBytesWritten(numberOfBytes);
  }

  @Override
  public void exceptionOccurred(DefaultHttpSocketMetric socketMetric, SocketAddress remoteAddress, Throwable t) {

  }

  @Override
  @Deprecated
  public boolean isEnabled() {
    return true;
  }

  @Override
  public void close() {

  }
}

@@ -1402,55 +1402,8 @@
 et;%0A
-import io.vertx.core.http.impl.HttpClientImpl;%0A
 impo
@@ -1438,16 +1438,16 @@
 ddress;%0A
+
 import i
@@ -3236,26 +3236,34 @@
   //
-only
+ as
  http
-1.1
+2 client
  will 
+not 
 invo
@@ -3282,149 +3282,159 @@
 od, 
-just make a check%0A    if (endpointMetric != null) %7B%0A      if (endpointMetric != socketMetric.getEndpointMetric()) %7B%0A        socketMetric.setE
+the endpointMetric info will lost.%0A    // you can get more details from https://github.com/eclipse-vertx/vert.x/issues/2660%0A    // hence, we will set e
 ndpo
@@ -3446,73 +3446,85 @@
 tric
-(endpointMetric);%0A      %7D%0A      endpointMetric.onConnect();%0A    %7D
+ info in the method connected(SocketAddress remoteAddress, String remoteName)
 %0A  %7D
@@ -5082,217 +5082,95 @@
 ) %7B%0A
-%0A
     
-DefaultHttpSocketMetric socketMetric = new DefaultHttpSocketMetric(null);%0A    try %7B%0A      DefaultHttpClientMetrics clientMetrics = (DefaultHttpClientMetrics) ((HttpClientImpl) client).getMetrics();%0A 
+//we can get endpointMetric info here, so set the endpointMetric info directly%0A
     
- 
 Defa
@@ -5220,20 +5220,11 @@
 c = 
-clientMetric
+thi
 s.cl
@@ -5249,18 +5249,16 @@
 Manager%0A
-  
         
@@ -5285,17 +5285,8 @@
 tric
-Map().get
 (rem
@@ -5306,279 +5306,102 @@
     
-  // set endPointMetric when use http2%0A      socketMetric.setEndpointMetric(clientEndpointMetric);%0A    %7D catch (Exception e) %7B%0A      LOGGER.warn(%22if you use http2, there may cause a null pointer exception. %7B%7D/%7B%7D%22, remoteAddress, remoteName);%0A    %7D%0A    return socke
+clientEndpointMetric.onConnect();%0A    return new DefaultHttpSocketMetric(clientEndpoin
 tMetric
+)
 ;%0A  

make http2 production ready: optimize endpointMetric set logic