package course.labs.fragmentslab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

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.TextView;

public class FeedFragment extends Fragment {

	
	private static final String TAG = "FeedFragment";
	private static final int[] IDS = {R.raw.ladygaga, R.raw.rebeccablack, R.raw.taylorswift};
	private static final int FEED_LENGTH = 100;
	
	
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

		 if (savedInstanceState != null) {
	       
	        }
		
		// Inflate the layout for this fragment
        return inflater.inflate(R.layout.feed, container, false);
    }
	
	@Override
    public void onStart() {
        super.onStart();

      
    }
	
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }
	
	private String procFeed(JSONArray feed){
		
		String name = "";
		String tweet = "";
		
		// string buffer for twitter feeds
		StringBuffer textFeed = new StringBuffer("");
		
		for(int j =0; j < FEED_LENGTH; j++){
			try {
				tweet = feed.getJSONObject(j).getString("text");
				JSONObject user = (JSONObject)feed.getJSONObject(j).get("user");
				name = user.getString("name");
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.i(TAG, "JSONException in get");
			}
			
			textFeed.append(name + " - " + tweet + "\n\n");
		}
		
		return textFeed.toString();
		
		
	}
	
	private JSONArray getFeed(int id){
		
		InputStream inputStream = getResources().openRawResource(id);
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String line = "";
		
		StringBuffer buffer = new StringBuffer("");
		
		try {
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
		} catch (IOException e) {
			Log.i(TAG, "IOException");
			return null;
		}

		// Turn the raw file into JSONArray
		
		JSONArray feed;
		try {
			feed = new JSONArray(buffer.toString());
		} catch (JSONException e) {
			Log.i(TAG, "JSONException");
			return null;
		}
		return feed;
	}
	
}
