package br.com.detetivesprofissionais.localizacao;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class HttpHelper {

    public interface Callback {
        void onResult(boolean ok, String body);
    }

    public static void postForm(final String urlString, final Map<String, String> params, final Callback callback) {
        new Thread(() -> {
            boolean ok = false;
            String body = "";

            try {
                StringBuilder postData = new StringBuilder();

                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (postData.length() > 0) postData.append('&');
                    postData.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }

                byte[] bytes = postData.toString().getBytes("UTF-8");

                URL url = new URL(urlString);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setConnectTimeout(10000);
                con.setReadTimeout(15000);
                con.setDoOutput(true);
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                con.setFixedLengthStreamingMode(bytes.length);

                OutputStream os = con.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();

                int code = con.getResponseCode();
                InputStream is = (code >= 200 && code < 400)
                        ? con.getInputStream()
                        : con.getErrorStream();

                if (is != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String line;

                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                    body = sb.toString();
                    br.close();
                }

                ok = code >= 200 && code < 300;

            } catch (Exception e) {
                body = e.getMessage() == null ? "Erro de comunicação" : e.getMessage();
            }

            final boolean finalOk = ok;
            final String finalBody = body;

            new Handler(Looper.getMainLooper()).post(() -> callback.onResult(finalOk, finalBody));
        }).start();
    }

    public static boolean jsonOk(String body) {
        try {
            JSONObject obj = new JSONObject(body);
            return obj.optBoolean("ok", false);
        } catch (Exception e) {
            return false;
        }
    }
}
