package io.keiji.whereami;

import android.util.Log;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Geocoding APIの利用をまとめたクラス.
 */
public class GeocodingApi {
    private static final String TAG = GeocodingApi.class.getSimpleName();

    public static Data getAddressByLocation(double latitude, double longitude) throws IOException {

        // 与えられた緯度(latitude)と経度(longitude)から、逆ジオコーディングをリクエストするURLを構築する
        URL url = new URL(
                String.format(Locale.JAPAN, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true", latitude, longitude));

        // 指定したURLに接続
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        StringBuilder sb = new StringBuilder();
        String line = null;

        // サーバーからの応答を読み取って文字列にする
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        String jsonString = sb.toString();

        Data data = null;
        try {
            data = new Data(jsonString);
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
        }

        br.close();

        return data;
    }

    public static class Data {

        public final List<Result> resultList = new ArrayList<>();

        public Data(String jsonString) throws JSONException {
            JSONObject jsonObject = new JSONObject(jsonString);

            JSONArray results = jsonObject.getJSONArray("results");
            int len = results.length();
            for (int i = 0; i < len; i++) {
                JSONObject resultObj = results.getJSONObject(i);
                Result result = new Result(resultObj);
                resultList.add(result);
            }
        }

        public class Result {

            public String formattedAddress;

            public Result(JSONObject resultObj) throws JSONException {
                formattedAddress = resultObj.getString("formatted_address");
            }
        }
    }

}
