package com.example.android.sunshine.app;

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.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

/**
 * A Forecast fragment containing a list view of forecast items.
 */
public class ForecastFragment extends Fragment {

    ArrayAdapter<String> mForecastItemAdapter;

    public ForecastFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forecastfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();
        if(id == R.id.action_refresh){
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute("32601");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        String[] fakeForecastDataString = {
                "Today - Rainy - 78/60",
                "Tomorrow - Sunny - 88/65",
                "Weds - Sunny - 88/66",
                "Thurs - Foggy - 88/66",
                "Fri - Cloudy - 88/66",
                "Sat - Sunny - 88/66",
                "Sun - Sunny - 88/66"
        };

        ArrayList<String> fakeForecastData = new ArrayList<>(Arrays.asList(fakeForecastDataString));

        mForecastItemAdapter =
                new ArrayAdapter<String>(
                        // Parent activity for context
                        getActivity(),
                        // layout for list item
                        R.layout.list_item_forecast,
                        // specific textview to populate
                        R.id.list_item_forecast_textview,
                        // data for textview
                        fakeForecastData);
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastItemAdapter);


        return rootView;
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String>{

        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();


        @Override
        protected String doInBackground(String... strings) {

            if(strings.length == 0){
                return null;
            }


            // 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 forecastJsonStr = null;
            String format = "json";
            String units = 'metric';
            int numDays = 7;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=32601&mode=json&units=metric&cnt=7";
                String apiKey = "&APPID=" + BuildConfig.OPEN_WEATHER_MAP_API_KEY;
                URL url = new URL(baseUrl.concat(apiKey));

                // Create the request to OpenWeatherMap, 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).append("\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
                Log.v(LOG_TAG, "Forecast JSON String: "+ forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                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 null;
        }
    }
}

@@ -36,16 +36,40 @@
 e.app;%0A%0A
+import android.net.Uri;%0A
 import a
@@ -3762,16 +3762,16 @@
 s = 
-'
+%22
 metric
-'
+%22
 ;%0A  
@@ -4043,24 +4043,64 @@
     
+final 
 String 
-baseUrl =
+FORECAST_BASE_URL =%0A                       
  %22ht
@@ -4155,44 +4155,209 @@
 ily?
-q=32601&mode=json&units=metric&
+%22;%0A                final String QUERY_PARAM = %22q%22;%0A                final String FORMAT_PARAM = %22mode%22;%0A                final String UNITS_PARAM = %22units%22;%0A                final String DAYS_PARAM = %22
 cnt
-=7
 %22;%0A 
@@ -4375,35 +4375,425 @@
     
+final 
 String 
-apiKey = %22&APPID=%22 +
+APPID_PARAM = %22APPID%22;%0A%0A                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()%0A                .appendQueryParameter(QUERY_PARAM, strings%5B0%5D)%0A                .appendQueryParameter(FORMAT_PARAM, format)%0A                .appendQueryParameter(UNITS_PARAM, units)%0A                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))%0A                .appendQueryParameter(APPID_PARAM,
  Bui
@@ -4825,17 +4825,44 @@
 _API_KEY
-;
+)%0A                .build();%0A
 %0A       
@@ -4893,28 +4893,94 @@
 RL(b
-aseUrl.concat(apiKey
+uiltUri.toString());%0A%0A                Log.v(LOG_TAG, %22Built URI %22 + builtUri.toString(
 ));%0A

build url with URIBuilder