package com.github.alinz.reactnativewebviewbridge;

import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.app.Activity;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.facebook.react.uimanager.ThemedReactContext;

class StatusBridge {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final String URL = "http://localhost:8545";

    private WebView webView;
    private ThemedReactContext context;
    private OkHttpClient client = new OkHttpClient();

    public StatusBridge(ThemedReactContext context, WebView webView) {
        this.context = context;
        this.webView = webView;
    }

    @JavascriptInterface
    public void sendRequest(final String callbackId, final String json) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                RequestBody body = RequestBody.create(JSON, json);
                Request request = new Request.Builder()
                        .url(URL)
                        .post(body)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String rpcResponse =  response.body().string().trim();

                    final String script = "httpCallback('" + callbackId + "','" + rpcResponse + "');";
                    final Activity activity = context.getCurrentActivity();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webView.evaluateJavascript(script, null);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }
}

@@ -1977,11 +1977,557 @@
 );%0A    %7D
+%0A%0A    @JavascriptInterface%0A    public String sendRequestSync(final String json) %7B%0A%0A        RequestBody body = RequestBody.create(JSON, json);%0A        Request request = new Request.Builder()%0A                .url(URL)%0A                .post(body)%0A                .build();%0A%0A        try (Response response = client.newCall(request).execute()) %7B%0A            String rpcResponse = response.body().string().trim();%0A%0A            return rpcResponse;%0A        %7D catch (IOException e) %7B%0A            e.printStackTrace();%0A%0A            return %22%22;%0A        %7D%0A    %7D
 %0A%7D%0A

add method for sync rpc request on android