package com.example.android.popularmovies;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class DiscoveryFragment extends Fragment {

    ArrayAdapter<String> mDiscoveryAdapter;

    public DiscoveryFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Create some mock data for the ListView.
        String[] data = {
                "MadMaxFuryRoad.jpg",
                "JurassicWorld.jpg",
                "AvengersLèredUltron.jpg",
                "AlaPoursuiteDeDemain.jpg",
                "LesMinions.jpg",
                "SanAndreas.jpg",
                "TerminatorGenisys.jpg"
        };
        List<String> imageNames = new ArrayList<String>(Arrays.asList(data));

        // The ArrayAdapter will take data and populate the GridView it's attached to.
        mDiscoveryAdapter = new ArrayAdapter<String>(getActivity(), R.layout.grid_item_layout, R.id.grid_item_layout, imageNames);

        View rootView = inflater.inflate(R.layout.fragment_discovery, container, false);


        // Get a reference to the ListView, and attach this adapter to it.
        GridView gridView = (GridView) rootView.findViewById(R.id.gridView_discovery);
        gridView.setAdapter(mDiscoveryAdapter);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        FetchMoviesTask movieTask = new FetchMoviesTask();
        movieTask.execute();
    }


    public class FetchMoviesTask extends AsyncTask<Void, Void, Void> {

        private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
        private final String API_KEY = "4691965cfc3e6f0591bc595986e92e84";

        @Override
        protected Void doInBackground(Void... params) {
            URL url = constructTMDbURL(API_KEY);
            Log.d("PopularMovies", url.toString());
            String forecastJsonStr = getJsonString(url);

            return null;
        }

        private URL constructTMDbURL(String key) {
            try {
                return new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=" + key);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error " + e);
                return null;
            }
        }


        private String getJsonString(URL url) {
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String moviesJsonStr = null;

            try {
                // Create the request http, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                moviesJsonStr = buffer.toString();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            return moviesJsonStr;
        }
    }

}

@@ -37,16 +37,40 @@
 ovies;%0A%0A
+import android.net.Uri;%0A
 import a
@@ -2120,16 +2120,33 @@
 execute(
+%22popularity.desc%22
 );%0A    %7D
@@ -2199,20 +2199,22 @@
 yncTask%3C
-Void
+String
 , Void, 
@@ -2432,20 +2432,22 @@
 kground(
-Void
+String
 ... para
@@ -2491,16 +2491,27 @@
 TMDbURL(
+params%5B0%5D, 
 API_KEY)
@@ -2621,17 +2621,16 @@
 g(url);%0A
-%0A
         
@@ -2701,16 +2701,36 @@
 (String 
+sortByValue, String 
 key) %7B%0A 
@@ -2766,106 +2766,512 @@
     
-return new URL(%22http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=%22 + key
+final String FORECAST_BASE_URL =%0A                        %22http://api.themoviedb.org/3/discover/movie?%22;%0A                final String SORTBY_PARAM = %22sort_by%22;%0A                final String KEY_PARAM = %22api_key%22;%0A%0A                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()%0A                        .appendQueryParameter(SORTBY_PARAM, sortByValue)%0A                        .appendQueryParameter(KEY_PARAM, key)%0A                        .build();%0A%0A                return new URL(builtUri.toString()
 );%0A 

Build URL with param sort_by