package com.criticalblue.reactnative;

import okhttp3.*;

import java.io.IOException;
import java.security.cert.Certificate;
import java.util.List;

import android.util.Log;

public class LoggingInterceptor implements Interceptor {
  private CertificatePinner certificatePinner;

  public LoggingInterceptor(CertificatePinner certificatePinner) {
    this.certificatePinner = certificatePinner;
  }

  @Override
  public Response intercept(Interceptor.Chain chain) throws IOException {
    Log.v("LoggingInterceptor", "Intercepting");
    String host = chain.request().url().host();
    Connection connection = chain.connection();
    Handshake handshake = connection != null ? connection.handshake() : null;
    List<Certificate> certs = handshake != null ? handshake.peerCertificates() : null;

    try {
      certificatePinner.check(host, certs);
      Log.v("LoggingInterceptor", "check OK for host " + host);
    } catch (Exception e) {
      Log.e("LoggingInterceptor", "check KO for host " + host);
      Log.e("LoggingInterceptor", e.getMessage());
      throw e;
    }
    return chain.proceed(chain.request());
  }
}