package com.samourai.wallet.bip47.paynym;

import android.content.Context;
import android.util.Log;

import com.samourai.wallet.BuildConfig;
import com.samourai.wallet.R;
import com.samourai.wallet.tor.TorManager;
import com.samourai.wallet.util.TorUtil;

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.NameValuePair;
import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity;
import ch.boye.httpclientandroidlib.client.methods.HttpDelete;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.client.methods.HttpPost;
import ch.boye.httpclientandroidlib.message.BasicNameValuePair;
import info.guardianproject.netcipher.client.StrongHttpsClient;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class WebUtil {

    public static final String PAYNYM_API = "https://paynym.is/";

    private static final int DefaultRequestRetry = 2;
    private static final int DefaultRequestTimeout = 60000;

    private static final String strProxyType = StrongHttpsClient.TYPE_SOCKS;
    private static final String strProxyIP = "127.0.0.1";
    private static final int proxyPort = 9050;

    private static WebUtil instance = null;
    private Context context = null;

    private WebUtil(Context ctx) {
        this.context = ctx;
    }

    public static WebUtil getInstance(Context ctx) {

        if (instance == null) {

            instance = new WebUtil(ctx);
        }

        return instance;
    }

    public String postURL(String request, String urlParameters) throws Exception {

        if (context == null) {
            return postURL(null, null, request, urlParameters);
        } else {
            Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast());
            if (TorUtil.getInstance(context).statusFromBroadcast()) {
                if (urlParameters.startsWith("tx=")) {
                    HashMap<String, String> args = new HashMap<String, String>();
                    args.put("tx", urlParameters.substring(3));
                    return tor_postURL(request, args);
                } else {
                    return tor_postURL(request + urlParameters, null);
                }
            } else {
                return postURL(null, null, request, urlParameters);
            }

        }

    }

    public String postURL(String contentType, String authToken, String requestURL, String urlParameters) throws Exception {

        String error = null;

        FormBody.Builder formBodyBuilder = new FormBody.Builder();

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .proxy(TorManager.getInstance(this.context).getProxy());

        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        Request request = new Request.Builder()
                .url(requestURL)
                .addHeader("Content-Type", contentType == null ? "application/x-www-form-urlencoded" : contentType)
                .post(formBodyBuilder.build())
                .build();

        try (Response response = builder.build().newCall(request).execute()) {
            if(response.body() == null){
                return  "";
            }
            return response.body().string();
        }

     }

    public String tor_postURL(String URL, HashMap<String, String> args) throws Exception {

        FormBody.Builder formBodyBuilder = new FormBody.Builder();

        if (args != null) {
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            for (String key : args.keySet()) {
                formBodyBuilder.add(key, args.get(key));
            }
        }

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .proxy(TorManager.getInstance(this.context).getProxy());

        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        Request request = new Request.Builder()
                .url(URL)
                .post(formBodyBuilder.build())
                .build();

        try (Response response = builder.build().newCall(request).execute()) {
            if(response.body() == null){
                return  "";
            }
            return response.body().string();
        }

    }

}

@@ -491,16 +491,43 @@
 et.URL;%0A
+import java.time.Duration;%0A
 import j
@@ -594,16 +594,54 @@
 il.List;
+%0Aimport java.util.concurrent.TimeUnit;
 %0A%0Aimport
@@ -1144,16 +1144,72 @@
 rmBody;%0A
+import okhttp3.MediaType;%0Aimport okhttp3.MultipartBody;%0A
 import o
@@ -1249,24 +1249,52 @@
 p3.Request;%0A
+import okhttp3.RequestBody;%0A
 import okhtt
@@ -3066,94 +3066,159 @@
     
-String error = null;%0A%0A        FormBody.Builder formBodyBuilder = new FormBody.Builder(
+MediaType JSON%0A                = MediaType.parse(%22application/json; charset=utf-8%22);%0A%0A        RequestBody body = RequestBody.create(JSON, urlParameters
 );%0A%0A
@@ -3278,34 +3278,36 @@
 nt.Builder()
+;%0A%0A
 %0A
- 
         
        .prox
@@ -3298,69 +3298,72 @@
     
-       .proxy(TorManager.getInstance(this.context).getProxy()
+builder.callTimeout(DefaultRequestTimeout, TimeUnit.MILLISECONDS
 );%0A%0A
@@ -3526,32 +3526,41 @@
      Request
- request
+.Builder rbuilder
  = new Reque
@@ -3720,16 +3720,18 @@
 entType)
+;%0A
 %0A       
@@ -3735,45 +3735,162 @@
     
-        .post(formBodyBuilder.build()
+if (authToken != null) %7B%0A            rbuilder.addHeader(%22auth-token%22, authToken);%0A        %7D%0A%0A        Request request = rbuilder%0A                .post(body
 )%0A  
@@ -3999,32 +3999,33 @@
 %7B%0A            if
+ 
 (response.body()
@@ -4025,32 +4025,33 @@
 .body() == null)
+ 
 %7B%0A              
@@ -4051,33 +4051,32 @@
          return 
- 
 %22%22;%0A            
@@ -4129,25 +4129,24 @@
 %0A        %7D%0A%0A
- 
     %7D%0A%0A    p

FIX : Paynym web request fix