package com.paulbsd;

import org.json.JSONException;
import org.json.JSONObject;

public class getIpInfo {

    // Main URL
    String url;

    // IP attributes
    private String ip = "undef";
    private String hostname = "undef";
    private String city = "undef";
    private String org = "undef";

    // Response
    String resp;

    getIpInfo(String url) throws Exception {
        this.url = url;

        System.out.println("Initiating connection to " + this.url);

        this.resp = getHTML(this.url);
        JSONObject reader = new JSONObject(resp);

        System.out.println("Terminating connection to " + this.url);

        try {
            this.ip = reader.getString("ip");
            this.hostname = reader.getString("hostname");
            this.city = reader.getString("city");
            this.org = reader.getString("org");
        } catch (JSONException jse) {
            System.out.println(jse);
        }
    }

    public static String getHTML(String urlToRead) throws IOException {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        return result.toString();
    }

    String getIp() {
        return this.ip;
    }

    String getHostname() {
        return this.hostname;
    }

    String getCity() {
        return this.city;
    }

    String getOrg() {
        return this.org;
    }
}
