/**@author David Westgate
 * SnipTease LLC.
 * 17 April 2014
 * */
package com.example.sniptease;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link FollowersFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link FollowersFragment#newInstance} factory
 * method to create an instance of this fragment.
 * 
 */
public class FollowersFragment extends Fragment {

	LinearLayout followingMeLayout;
	LinearLayout imFollowingLayout;
	RadioGroup followingViewSwitcher;
	Context context;

	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	private static final String ARG_PARAM1 = "param1";
	private static final String ARG_PARAM2 = "param2";

	// TODO: Rename and change types of parameters
	private String mParam1;
	private String mParam2;

	private OnFragmentInteractionListener mListener;

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment FriendsFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static FollowersFragment newInstance(String param1, String param2) {
		FollowersFragment fragment = new FollowersFragment();
		Bundle args = new Bundle();
		args.putString(ARG_PARAM1, param1);
		args.putString(ARG_PARAM2, param2);
		fragment.setArguments(args);
		return fragment;
	}

	public FollowersFragment() {
		// Required empty public constructor
	}

	LoadFollowingMeTask loadFollowingMe;
	LoadImFollowingTask loadImFollowing;

	@Override
	public void onStart() {
		super.onStart();
		loadImFollowing.execute();
		loadFollowingMe.execute();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			mParam1 = getArguments().getString(ARG_PARAM1);
			mParam2 = getArguments().getString(ARG_PARAM2);
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View rootview = inflater.inflate(R.layout.fragment_following,
				container, false);
		loadFollowingMe = new LoadFollowingMeTask();
		loadImFollowing = new LoadImFollowingTask();
		followingMeLayout = (LinearLayout) rootview
				.findViewById(R.id.following_me_container);
		imFollowingLayout = (LinearLayout) rootview
				.findViewById(R.id.im_following_container);
		RadioGroup radioGroup = (RadioGroup) rootview
				.findViewById(R.id.following_toggle_group);

		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// checkedId is the RadioButton selected

				switch (checkedId) {
				case R.id.following_me_toggle:
				
					followingMeLayout.setVisibility(View.VISIBLE);
					imFollowingLayout.setVisibility(View.GONE);

					break;
				case R.id.im_following_toggle:
					
					imFollowingLayout.setVisibility(View.VISIBLE);
					followingMeLayout.setVisibility(View.GONE);
					break;

				}
			}
		});
		return rootview;

	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}

	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}

	public class LoadFollowingMeTask extends AsyncTask<Void, Void, JSONArray> {
		ArrayList<Bitmap> userBitmaps;
		String username;

		@Override
		protected JSONArray doInBackground(Void... params) {
			String link = "http://23.253.210.151/jsonrequests.php?action=get_followers&username="
					+ LoginActivity.getUsername();
			HttpGet httpget = new HttpGet(link);
			try {
				HttpResponse httpresponce = LoginActivity.client.execute(
						httpget, LoginActivity.localContext);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(httpresponce.getEntity()
								.getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONArray jsonArray = new JSONArray(builder.toString());
				Log.d("JSONArray", jsonArray.toString(1));
				userBitmaps = new ArrayList<Bitmap>();
				for (int i = 0; !jsonArray.isNull(i); i++) {
					URL url = new URL(
							"http://23.253.210.151/uploads/profile_pictures/thumbs/"
									+ jsonArray.getJSONObject(i).getString(
											"username") + ".jpg");
					userBitmaps.add(Bitmap.createScaledBitmap(
							BitmapFactory.decodeStream(url.openStream()), 100,
							100, false));

				}

				return jsonArray;
			} catch (IOException | JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}

		}

		@Override
		protected void onPostExecute(JSONArray jsonArray) {
			for (int i = 0; !jsonArray.isNull(i); i++) {
			
				try {

					
					LinearLayout followingMeContainer = new LinearLayout(
							getActivity());
					TextView userNameTextView = new TextView(getActivity());
					userNameTextView.setText(jsonArray.getJSONObject(i)
							.getString("username"));

				
					
					if (!jsonArray.getJSONObject(i).getString("status").equalsIgnoreCase("complete")){
							userNameTextView.setText(userNameTextView.getText()+"\n"+jsonArray.getJSONObject(i).getString("status"));
					}

					ImageView thisImage = new ImageView(getActivity());
					thisImage.setImageBitmap(userBitmaps.get(i));

					followingMeContainer
							.setOrientation(LinearLayout.HORIZONTAL);
					followingMeContainer.addView(thisImage);
					followingMeContainer.addView(userNameTextView);
					
					followingMeContainer
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Log.d("tag", "onclick following me");
							LinearLayout linearLayout = (LinearLayout) v;
							TextView tv = (TextView) linearLayout.getChildAt(1);
							Intent intent = new Intent(getActivity(),
									ViewAProfileActivity.class);
							intent.putExtra("username", tv.getText().toString());
							startActivity(intent);

						}

					});
					followingMeLayout.addView(followingMeContainer);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public class LoadImFollowingTask extends AsyncTask<Void, Void, JSONArray> {

		ArrayList<Bitmap> userBitmaps;
		

		@Override
		protected JSONArray doInBackground(Void... params) {
			String link = "http://23.253.210.151/jsonrequests.php?action=get_following&username="
					+ LoginActivity.getUsername();
			HttpGet httpget = new HttpGet(link);
			try {
				HttpResponse httpresponce = LoginActivity.client.execute(
						httpget, LoginActivity.localContext);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(httpresponce.getEntity()
								.getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONArray jsonArray = new JSONArray(builder.toString());
				Log.d("JSONArray", jsonArray.toString(1));
				userBitmaps = new ArrayList<Bitmap>();
				for (int i = 0; !jsonArray.isNull(i); i++) {
					URL url = new URL(
							"http://23.253.210.151/uploads/profile_pictures/thumbs/"
									+ jsonArray.getJSONObject(i).getString(
											"username") + ".jpg");
					userBitmaps.add(Bitmap.createScaledBitmap(
							BitmapFactory.decodeStream(url.openStream()), 100,
							100, false));

				}

				return jsonArray;
			} catch (IOException | JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}

		}

		@Override
		protected void onPostExecute(JSONArray jsonArray) {
			for (int i = 0; !jsonArray.isNull(i); i++) {
			
				try {

					
					LinearLayout followingMeContainer = new LinearLayout(
							getActivity());
					TextView userNameTextView = new TextView(getActivity());
					userNameTextView.setText(jsonArray.getJSONObject(i)
							.getString("username"));

					TextView statusTextView = new TextView(getActivity());
					statusTextView.setText(jsonArray.getJSONObject(i)
							.getString("status"));
				
					if (!jsonArray.getJSONObject(i).getString("status").equalsIgnoreCase("complete")) {
						
						userNameTextView.setText(userNameTextView.getText()+"\n"+jsonArray.getJSONObject(i).getString("status"));
					}

					ImageView thisImage = new ImageView(getActivity());
					thisImage.setImageBitmap(userBitmaps.get(i));

					followingMeContainer
							.setOrientation(LinearLayout.HORIZONTAL);
					followingMeContainer.addView(thisImage);
					followingMeContainer.addView(userNameTextView);
					
					followingMeContainer
							.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									Log.d("tag", "onclick im following ");
									LinearLayout linearLayout = (LinearLayout) v;
									TextView tv = (TextView) linearLayout.getChildAt(1);
									Intent intent = new Intent(getActivity(),
											ViewAProfileActivity.class);
									intent.putExtra("username", tv.getText().toString());
									startActivity(intent);

								}

							});
					imFollowingLayout.addView(followingMeContainer);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}
