package jp.toastkid.search_widget.search.suggest;

import android.support.annotation.NonNull;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.functions.Consumer;
import jp.toastkid.search_widget.libs.Utf8StringEncoder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Suggest Web API response fetcher.
 *
 * @author toastkidjp
 */
public class SuggestFetcher {

    /** Suggest Web API. */
    private static final String URL
            = "https://www.google.com/complete/search?hl=ja&output=toolbar&q=";

    /** HTTP client. */
    private OkHttpClient mClient;

    /**
     * Initialize HTTP client.
     */
    public SuggestFetcher() {
        mClient = new OkHttpClient.Builder()
                .connectTimeout(3L, TimeUnit.SECONDS)
                .readTimeout(3L, TimeUnit.SECONDS)
                .build();
    }

    /**
     * Fetch Web API result asynchronously.
     *
     * @param query
     * @param consumer
     */
    public void fetchAsync(final String query, final Consumer<List<String>> consumer) {
        final Request request = new Request.Builder()
                .url(URL + Utf8StringEncoder.encode(query))
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(
                    final Call call,
                    @NonNull final Response response
            ) throws IOException {
                if (response.body() == null) {
                    return;
                }
                try {
                    consumer.accept(new SuggestParser().parse(response.body().string()));
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

@@ -86,16 +86,41 @@
 NonNull;
+%0Aimport android.util.Log;
 %0A%0Aimport
@@ -160,24 +160,49 @@
 .util.List;%0A
+import java.util.Locale;%0A
 import java.
@@ -264,24 +264,70 @@
 s.Consumer;%0A
+import jp.toastkid.search_widget.libs.Logger;%0A
 import jp.to
@@ -719,13 +719,8 @@
 rch?
-hl=ja
 &out
@@ -734,11 +734,8 @@
 lbar
-&q=
 %22;%0A%0A
@@ -1330,38 +1330,22 @@
 url(
-URL + Utf8StringEncoder.encode
+makeSuggestUrl
 (que
@@ -2080,32 +2080,32 @@
 %7D%0A            %7D%0A
-
         %7D);%0A    
@@ -2105,11 +2105,351 @@
 );%0A    %7D
+%0A%0A    /**%0A     * Make suggest Web API requesting URL.%0A     * @param query Query%0A     * @return suggest Web API requesting URL%0A     */%0A    @NonNull%0A    private String makeSuggestUrl(@NonNull final String query) %7B%0A        return URL + %22&hl=%22 + Locale.getDefault().getLanguage()%0A                + %22&q=%22 + Utf8StringEncoder.encode(query);%0A    %7D
 %0A%7D%0A

Modify using suggest.