package com.zatackcoder.searchviewsuggestionsovernetwork;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.RecyclerView;

import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

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

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private SuggestionAdapter suggestionAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_main_activity, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) getApplicationContext().getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = null;
        if (searchItem != null) {
            searchView = (SearchView) searchItem.getActionView();
        }
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String s) {
                    new GetSuggestionsAsyncTask(MainActivity.this, s).execute();
                    return false;
                }
            });
            suggestionAdapter = new SuggestionAdapter(getApplicationContext(), null, false);
            searchView.setSuggestionsAdapter(suggestionAdapter);
        }
        return super.onCreateOptionsMenu(menu);
    }

    static class GetSuggestionsAsyncTask extends AsyncTask<Void, Void, Cursor> {

        private final WeakReference<MainActivity> activityReference;
        final String term;

        GetSuggestionsAsyncTask(MainActivity context, String term) {
            this.activityReference = new WeakReference<>(context);
            this.term = term;
        }

        @Override
        protected Cursor doInBackground(Void... voids) {
            HashMap<String, String> params = new HashMap<>();
            params.put("key", "SECUREKEY");
            params.put("action", "get-search-suggestions");
            params.put("term", term);

            JsonParser jsonParser = new JsonParser();
            JSONObject jsonObject = jsonParser.get("https://zatackcoder.com/demo/searchview-suggestion-over-network/api.php", params);

            MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, "name", "color", "size", "price"});

            if (jsonObject != null) {
                try {
                    JSONArray dataJsonArray = jsonObject.getJSONArray("data");
                    int j = 0;
                    for (int i = 0; i < dataJsonArray.length(); i++) {
                        JSONObject tmp = dataJsonArray.getJSONObject(i);
                        String[] row = {Integer.toString(j++), tmp.getString("name"), tmp.getString("color"), tmp.getString("size"), tmp.getString("price")};
                        cursor.addRow(row);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return cursor;
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            super.onPostExecute(cursor);
            MainActivity mainActivity = activityReference.get();
            if(mainActivity == null || mainActivity.isFinishing()) {
                return;
            }
            mainActivity.suggestionAdapter.changeCursor(cursor);
        }
    }
}
