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.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

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.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
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 {

        MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        RequestBody body = RequestBody.create(JSON, urlParameters);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();


        builder.callTimeout(DefaultRequestTimeout, TimeUnit.MILLISECONDS);

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

        if (authToken != null) {
            rbuilder.addHeader("auth-token", authToken);
        }

        Request request = rbuilder
                .post(body)
                .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();
        }

    }

}

@@ -71,33 +71,8 @@
 ext;
-%0Aimport android.util.Log;
 %0A%0Aim
@@ -113,38 +113,8 @@
 ig;%0A
-import com.samourai.wallet.R;%0A
 impo
@@ -156,855 +156,47 @@
 er;%0A
-import com.samourai.wallet.util.TorUtil;%0A%0Aimport org.apache.commons.io.IOUtils;%0A%0Aimport java.io.BufferedReader;%0Aimport java.io.DataOutputStream;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader;%0Aimport java.net.HttpURLConnection;%0Aimport java.net.URI;%0Aimport java.net.URL;%0Aimport java.time.Duration;%0Aimport java.util.ArrayList;%0Aimport java.util.HashMap;%0Aimport java.util.List;%0Aimport java.util.concurrent.TimeUnit;%0A%0Aimport ch.boye.httpclientandroidlib.HttpResponse;%0Aimport ch.boye.httpclientandroidlib.NameValuePair;%0Aimport ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity;%0Aimport ch.boye.httpclientandroidlib.client.methods.HttpDelete;%0Aimport ch.boye.httpclientandroidlib.client.methods.HttpGet;%0Aimport ch.boye.httpclientandroidlib.client.methods.HttpPost;%0Aimport ch.boye.httpclientandroidlib.message.BasicNameValuePair;
+%0Aimport java.util.concurrent.TimeUnit;%0A
 %0Aimp
@@ -260,33 +260,8 @@
 nt;%0A
-import okhttp3.FormBody;%0A
 impo
@@ -286,38 +286,8 @@
 pe;%0A
-import okhttp3.MultipartBody;%0A
 impo
@@ -1151,872 +1151,8 @@
  %7D%0A%0A
-    public String postURL(String request, String urlParameters) throws Exception %7B%0A%0A        if (context == null) %7B%0A            return postURL(null, null, request, urlParameters);%0A        %7D else %7B%0A            Log.i(%22WebUtil%22, %22Tor enabled status:%22 + TorUtil.getInstance(context).statusFromBroadcast());%0A            if (TorUtil.getInstance(context).statusFromBroadcast()) %7B%0A                if (urlParameters.startsWith(%22tx=%22)) %7B%0A                    HashMap%3CString, String%3E args = new HashMap%3CString, String%3E();%0A                    args.put(%22tx%22, urlParameters.substring(3));%0A                    return tor_postURL(request, args);%0A                %7D else %7B%0A                    return tor_postURL(request + urlParameters, null);%0A                %7D%0A            %7D else %7B%0A                return postURL(null, null, request, urlParameters);%0A            %7D%0A%0A        %7D%0A%0A    %7D%0A%0A
     
@@ -2032,32 +2032,177 @@
 oken);%0A        %7D
+%0A        if(TorManager.getInstance(context).isConnected())%7B%0A            builder.proxy(TorManager.getInstance(this.context).getProxy());%0A        %7D
 %0A%0A        Reques
@@ -2507,1069 +2507,8 @@
  %7D%0A%0A
-    public String tor_postURL(String URL, HashMap%3CString, String%3E args) throws Exception %7B%0A%0A        FormBody.Builder formBodyBuilder = new FormBody.Builder();%0A%0A        if (args != null) %7B%0A            List%3CNameValuePair%3E urlParameters = new ArrayList%3CNameValuePair%3E();%0A            for (String key : args.keySet()) %7B%0A                formBodyBuilder.add(key, args.get(key));%0A            %7D%0A        %7D%0A%0A        OkHttpClient.Builder builder = new OkHttpClient.Builder()%0A                .proxy(TorManager.getInstance(this.context).getProxy());%0A%0A        if (BuildConfig.DEBUG) %7B%0A            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));%0A        %7D%0A        Request request = new Request.Builder()%0A                .url(URL)%0A                .post(formBodyBuilder.build())%0A                .build();%0A%0A        try (Response response = builder.build().newCall(request).execute()) %7B%0A            if(response.body() == null)%7B%0A                return  %22%22;%0A            %7D%0A            return response.body().string();%0A        %7D%0A%0A    %7D
 %0A%0A%7D%0A

Use Tor proxy when interacting with paynym api