/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.asynctaskloader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.android.asynctaskloader.utilities.NetworkUtils;

import java.io.IOException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    // TODO (1) Create a static final key to store the query's URL

    // TODO (2) Create a static final key to store the search's raw JSON

    private EditText mSearchBoxEditText;

    private TextView mUrlDisplayTextView;
    private TextView mSearchResultsTextView;

    private TextView mErrorMessageDisplay;

    private ProgressBar mLoadingIndicator;

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

        mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);

        mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
        mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);

        mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);

        mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);

        // TODO (9) If the savedInstanceState bundle is not null, set the text of the URL and search results TextView respectively
    }

    /**
     * This method retrieves the search text from the EditText, constructs the
     * URL (using {@link NetworkUtils}) for the github repository you'd like to find, displays
     * that URL in a TextView, and finally fires off an AsyncTask to perform the GET request using
     * our {@link GithubQueryTask}
     */
    private void makeGithubSearchQuery() {
        String githubQuery = mSearchBoxEditText.getText().toString();
        URL githubSearchUrl = NetworkUtils.buildUrl(githubQuery);
        mUrlDisplayTextView.setText(githubSearchUrl.toString());
        new GithubQueryTask().execute(githubSearchUrl);
    }

    /**
     * This method will make the View for the JSON data visible and
     * hide the error message.
     * <p>
     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showJsonDataView() {
        /* First, make sure the error is invisible */
        mErrorMessageDisplay.setVisibility(View.INVISIBLE);
        /* Then, make sure the JSON data is visible */
        mSearchResultsTextView.setVisibility(View.VISIBLE);
    }

    /**
     * This method will make the error message visible and hide the JSON
     * View.
     * <p>
     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showErrorMessage() {
        /* First, hide the currently visible data */
        mSearchResultsTextView.setVisibility(View.INVISIBLE);
        /* Then, show the error */
        mErrorMessageDisplay.setVisibility(View.VISIBLE);
    }

    public class GithubQueryTask extends AsyncTask<URL, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mLoadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(URL... params) {
            URL searchUrl = params[0];
            String githubSearchResults = null;
            try {
                githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return githubSearchResults;
        }

        @Override
        protected void onPostExecute(String githubSearchResults) {
            mLoadingIndicator.setVisibility(View.INVISIBLE);
            if (githubSearchResults != null && !githubSearchResults.equals("")) {
                showJsonDataView();
                mSearchResultsTextView.setText(githubSearchResults);
            } else {
                showErrorMessage();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemThatWasClickedId = item.getItemId();
        if (itemThatWasClickedId == R.id.action_search) {
            makeGithubSearchQuery();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // TODO (3) Override onSaveInstanceState to persist data across Activity recreation
    // Do the following steps within onSaveInstanceState
    // TODO (4) Make sure super.onSaveInstanceState is called before doing anything else

    // TODO (5) Put the contents of the TextView that contains our URL into a variable
    // TODO (6) Using the key for the query URL, put the string in the outState Bundle

    // TODO (7) Put the contents of the TextView that contains our raw JSON search results into a variable
    // TODO (8) Using the key for the raw JSON search results, put the search results into the outState Bundle
}
@@ -1125,20 +1125,25 @@
 %0A    // 
-TODO
+completed
  (1) Cre
@@ -1190,28 +1190,76 @@
 y's URL%0A
-%0A    // TODO
+    private static final String qURL = %22%22;%0A%0A    // completed
  (2) Cre
@@ -1311,16 +1311,60 @@
 raw JSON
+%0A    private static final String rJSON = %22%22;
 %0A%0A    pr
@@ -2288,16 +2288,165 @@
 ctively%0A
+        if (savedInstanceState != null)%7B%0A            mUrlDisplayTextView.setText(qURL);%0A            mSearchResultsTextView.setText(rJSON);%0A        %7D%0A
     %7D%0A%0A 
@@ -5673,20 +5673,25 @@
 %0A    // 
-TODO
+completed
  (3) Ove
@@ -5823,20 +5823,25 @@
 %0A    // 
-TODO
+completed
  (4) Mak
@@ -5918,20 +5918,25 @@
 %0A    // 
-TODO
+completed
  (5) Put
@@ -6010,20 +6010,25 @@
 %0A    // 
-TODO
+completed
  (6) Usi
@@ -6103,20 +6103,25 @@
 %0A    // 
-TODO
+completed
  (7) Put
@@ -6215,20 +6215,25 @@
 %0A    // 
-TODO
+completed
  (8) Usi
@@ -6324,9 +6324,369 @@
  Bundle%0A
+    @Override%0A    protected void onSaveInstanceState(Bundle outState)%7B%0A        super.onSaveInstanceState(outState);%0A%0A%0A        String queryURL = mUrlDisplayTextView.getText().toString();%0A        outState.putString(qURL, queryURL);%0A%0A        String jsonResults = mSearchResultsTextView.getText().toString();%0A        outState.putString(rJSON, jsonResults);%0A%0A    %7D%0A
 %7D

complete TODO 1-9