package com.example.fitbot.util;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;

import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

public class Networking {

    public static void sendIpAddress(final Context context) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                String ipAddress = getIPAddress(context);
                String jsonInputString = "{\"ip\":\"" +
                        ipAddress +
                        "\"}";

                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                HttpURLConnection conn = null;
                try {
                    URL url = new URL("http://145.92.8.132:443/set-ip"); // Replace with your Node server URL
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setDoOutput(true);

                    OutputStream os = conn.getOutputStream();
                    os.write(input, 0, input.length);
                    os.close();

                    int responseCode = conn.getResponseCode();
                    Log.i("NetworkUtils", "Response Code: " + responseCode);
                } catch (Exception e) {
                    Log.e("NetworkUtils", "Error sending IP address", e);
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
                return null;
            }
        }.execute();
    }


    private static String getIPAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();

        // Convert little-endian to big-endian if needed
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            ipAddress = Integer.reverseBytes(ipAddress);
        }

        byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

        String ip = "";
        try {
            ip = InetAddress.getByAddress(ipByteArray).getHostAddress();
        } catch (UnknownHostException ex) {
            Log.e("WIFIIP", "Unable to get host address.");
        }

        return ip;
    }
}