package com.example.android.movies;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView mTextViewQueryResults;
    private TextView mTextViewErrorMessage;
    private ProgressBar mProgressBarQuery;
    private ArrayList<Movie> arrayListMovies = new ArrayList<Movie>();

    /*
    //TODO: Uncomment this to try query after network state changes.
    BroadcastReceiver broadcastReceiverConnectivity = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            queryMoviesDb();
        }
    };

    IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextViewQueryResults = (TextView) findViewById(R.id.tv_query_results);
        mTextViewErrorMessage = (TextView) findViewById(R.id.tv_error_message);
        mProgressBarQuery = (ProgressBar) findViewById(R.id.pb_query);
        queryMoviesDb(MovieCategories.POPULAR);
        /*
        //TODO: Uncomment this to try query after network state changes.
        try {
            registerReceiver(broadcastReceiverConnectivity, intentFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
    }

    public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null &&
                cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }

    private void queryMoviesDb(MovieCategories movieCategories) {
        URL moviesQueryUrl = NetworkUtilities.buildUrl(movieCategories);
        new MoviesQueryTask().execute(moviesQueryUrl);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.query, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_query_now_playing_movies:
                mTextViewQueryResults.setText("");
                queryMoviesDb(MovieCategories.NOW_PLAYING);
                return true;
            case R.id.action_query_popular_movies:
                mTextViewQueryResults.setText("");
                queryMoviesDb(MovieCategories.POPULAR);
                return true;
            case R.id.action_query_top_rated_movies:
                mTextViewQueryResults.setText("");
                queryMoviesDb(MovieCategories.TOP_RATED);
                return true;
            case R.id.action_query_upcoming_movies:
                mTextViewQueryResults.setText("");
                queryMoviesDb(MovieCategories.UPCOMING);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showJsonDataView() {
        mTextViewQueryResults.setVisibility(View.VISIBLE);
        mTextViewErrorMessage.setVisibility(View.INVISIBLE);
    }

    private void showErrorMessage() {
        mTextViewErrorMessage.setVisibility(View.VISIBLE);
        mTextViewQueryResults.setVisibility(View.INVISIBLE);
    }

    public class MoviesQueryTask extends AsyncTask<URL, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressBarQuery.setVisibility(View.VISIBLE);
        }
        @Override
        protected String doInBackground(URL... urls) {
            URL searchUrl = urls[0];
            String moviesQueryResults = null;
            if (isOnline()) {
                Log.d(TAG, "Query working while online.");
                try {
                    moviesQueryResults = NetworkUtilities.getResponseFromHttpUrl(searchUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.d(TAG, "Query will not work while offline.");
            }
            return moviesQueryResults;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mProgressBarQuery.setVisibility(View.INVISIBLE);
            if (s != null && !s.equals("")) {
                mTextViewQueryResults.setText(s);
                showJsonDataView();
                analyzeJson(s);
            } else {
                showErrorMessage();
            }
        }

        void analyzeJson(String stringJson) {
            if (!arrayListMovies.isEmpty()) {
                arrayListMovies.clear();
            }

            try {
                JSONObject jsonObjectResults = new JSONObject(stringJson);
                JSONArray jsonArrayMovies = jsonObjectResults.getJSONArray("results");

                for(int i=0; i<jsonArrayMovies.length(); i++){
                    JSONObject jsonObjectMovie = jsonArrayMovies.getJSONObject(i);

                    Movie movie = new Movie(
                            jsonObjectMovie.getString("title"),
                            jsonObjectMovie.getString("release_date"),
                            jsonObjectMovie.getString("poster_path"),
                            jsonObjectMovie.getString("vote_average"),
                            jsonObjectMovie.getString("overview"));
                    arrayListMovies.add(movie);
                }

                for (int i=0; i<arrayListMovies.size(); i++) {
                    Log.d(TAG, arrayListMovies.get(i).title);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    // Credits to http://stackoverflow.com/a/25734136 post.
    public static void largeLog(String tag, String content) {
        if (content.length() > 4000) {
            Log.d(tag, content.substring(0, 4000));
            largeLog(tag, content.substring(4000));
        } else {
            Log.d(tag, content);
        }
    }
}



@@ -550,16 +550,39 @@
 rayList;
+%0Aimport java.util.List;
 %0A%0Apublic
@@ -846,21 +846,16 @@
 private 
-Array
 List%3CMov
@@ -858,22 +858,17 @@
 %3CMovie%3E 
-arrayL
+l
 istMovie
@@ -889,402 +889,12 @@
 ist%3C
-Movie%3E();%0A%0A    /*%0A    //TODO: Uncomment this to try query after network state changes.%0A    BroadcastReceiver broadcastReceiverConnectivity = new BroadcastReceiver() %7B%0A        @Override%0A        public void onReceive(Context context, Intent intent) %7B%0A            queryMoviesDb();%0A        %7D%0A    %7D;%0A%0A    IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);%0A    */%0A
+%3E();
 %0A   
@@ -1284,16 +1284,16 @@
 query);%0A
+
         
@@ -1336,267 +1336,8 @@
 R);%0A
-        /*%0A        //TODO: Uncomment this to try query after network state changes.%0A        try %7B%0A            registerReceiver(broadcastReceiverConnectivity, intentFilter);%0A        %7D catch (Exception e) %7B%0A            e.printStackTrace();%0A        %7D%0A        */%0A
     
@@ -4618,22 +4618,17 @@
    if (!
-arrayL
+l
 istMovie
@@ -4650,38 +4650,33 @@
                 
-arrayL
+l
 istMovies.clear(
@@ -5430,22 +5430,17 @@
         
-arrayL
+l
 istMovie
@@ -5502,20 +5502,18 @@
 nt i
-=
+ = 
 0; i%3C
-arrayL
+ l
 istM
@@ -5568,14 +5568,9 @@
 AG, 
-arrayL
+l
 istM
@@ -5718,340 +5718,8 @@
    %7D
-%0A%0A    // Credits to http://stackoverflow.com/a/25734136 post.%0A    public static void largeLog(String tag, String content) %7B%0A        if (content.length() %3E 4000) %7B%0A            Log.d(tag, content.substring(0, 4000));%0A            largeLog(tag, content.substring(4000));%0A        %7D else %7B%0A            Log.d(tag, content);%0A        %7D%0A    %7D
 %0A%7D%0A%0A

Remove unused code.